PHP chr() Function To Convert Byte To Character/String – POFTUT

PHP chr() Function To Convert Byte To Character/String


PHP provides the chr() function in order to convert the given number into a single character or string. Even it is called byte value it is an integer which can be between 0 and 255.

Convert Byte To Char

In the following example, we will convert the given byte values or integers into a character or string. The syntax is very simple where the byte value is provided as a parameter and the single character or string is returned.

STRING = chr(BYTE_VALUE);
  • STRING is the string or character type variable where the BYTE_VALUE character representation will be assigned.
  • BYTE_VALUE is the value we want to convert to the char or string.
$str = chr(240) . chr(159) . chr(144) . chr(152);
echo $str;
#The output will be ?


$str = chr(144);
echo $str;
#The output will be �

$str = chr(89);
echo $str;
# Output will be Y

$str = chr(88);
echo $str;
#The output will be X

$str = chr(87);
echo $str;
#The output will be W
Convert Byte To Char

If The Value Is Higher Than 256

In some cases, the value can be higher than the 256 which is the limit of the chr() function. Or the value can be lower than the 0 as a negative number like -56. In this case, the mod operation is implemented were given out of range values will be converted between 0 and 256.

$str = chr(-169);
echo $str;
#The output will be W


$str = chr(87);
echo $str;
#The output will be W


$str = chr(-170);
echo $str;
#The output will be V


$str = chr(86);
echo $str;
#The output will be V


$str = chr(342);
echo $str;
#The output will be V
If The Value Is Higher Than 256

ASCII Table

chr() function uses the ASCII table for byte value or integer value into a single character or string conversion. ASCII table provides the given single character numeric equation like below. For example, 62 will be converted into the < sign.

ASCII Table

Leave a Comment