PHP function chr() – Generate a single-byte string from a number

The chr() function returns a single character string from an ASCII value that is already specified. If the integer provided is not a valid ASCII code, the function returns nothing. This function was introduced in PHP3.

Note that the integer can be specified in octal or hex values, as well as decimal. Octal values are denoted by a leading 0 (07, 012, …), while hex values are denoted by a leading 0x (0xFF, 0x9D, …).

The ord() function does the opposite of chr(): it takes a string and returns the equivalent ASCII value.

Syntax:

chr(int $codepoint): string

Parameters

Parameter Description
codepoint An integer between 0 and 255.

Values outside the valid range (0..255) will be bitwise and’ed with 255, which is equivalent to the following algorithm:

while ($bytevalue 

Return Values

A single-character string containing the specified byte.

Examples

Example 1: Add a null byte to the end of a string.

$string .= chr (0); 

Example 2: Find the character for a hex value.

<?php 
// Sesame Street for budding geeks 
echo "The ASCII character code for today is 0x57...", chr (0x57); 
?>

Output:

The ASCII character code for today is 0x57...W 

Example 3:

<?php
$string .= chr(27); /* include an escape charac- ter at the end of $string */
/* This will often help */$string = sprintf(“The defined string will end in escape: %c”, 27);
?>

Example 4:

<?php
// Assumes the string will be used as ASCII or an ASCII-compatible encoding

$str = "The string ends in escape: ";
$str .= chr(27); /* add an escape character at the end of $str */
/* Often this is more useful */$str = sprintf("The string ends in escape: %c", 27);
?>

Example 5: Overflow behavior.

<?php
echo chr(-159), chr(833), PHP_EOL;
?>

The above example will output:

aA

Example 6: Building a UTF-8 string from individual bytes.

<?php
$str = chr(240) . chr(159) . chr(144) . chr(152);
echo $str;
?>

The above example will output:

🐘

Example 7:

$letter = chr(109);
print "ASCII number 109 is equivalent to $letter\n";

That would output "ASCII number 109 is equivalent to m".

Related Post