PHP 8 reference · String Functions

PHP bin2hex() Function

Convert binary data to a hexadecimal string, two hex digits per byte. Often used to print random bytes as a token.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

bin2hex(string $string): string

Parameters

ParameterDescription
string The input string.

Return value

The hex string, twice as long as the input.

Examples

To hex and backTry it yourself
<?php
echo bin2hex("abc"), "\n";
echo hex2bin("616263"), "\n";

Output

616263
abc
A random tokenTry it yourself
<?php
$token = bin2hex(random_bytes(16));
echo strlen($token), "\n";

Output

32

Version history

VersionChange
PHP 4.0Added

Was this page helpful?