chr GENERATE a single-byte string from a number.
This function a one-character string containing the character specified by interpreting $bytevalue as an unsigned integer.
This can be used to create a one-character string in a single-byte encoding such as ASCII, ISO-8859, or Windows 1252, tby passing the position of a desired character in the encoding's mapping table.
However, note that this function is not aware of any string encoding, and in particular cannot be passed a Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16.
This function complements ord.
<?php
str chr ( int $bytevalue )
where,
$bytevalue = An integer between 0 and 255
?>
$bytevalue
An integer between 0 and 255.
EXERCISE
<table width="100%" cellspacing="5" cellpadding="5"
border="1" align="center">
<tbody><tr><td colspan="2">ord/chr</td></tr><tr>
<td width="30%">ord</td><td>chr</td></tr>
<?php
for ($ord01 = 0; $ord01 <= 255; $ord01++)
{
echo '<tr><td>' . $ord01 . '</td><td>' . chr($ord01) . '</td></tr>';
}
?>
<tr><td colspan="2">ed48</td></tr></tbody></table>
EXERCISE
<?php
echo "Testing chr() : basic functionality.<br><br>";
echo chr(72). chr(101) . chr(108) . chr(108). chr(111);
// Hello
echo chr(10);
// "<br>"
echo "World";
?>
RESULT
Testing chr() : basic functionality.
Hello World
EXERCISE
<?php
echo "Testing chr() function:
with unexpected inputs for 'ascii' argument.";
//get an unset variable
$unset_var = 'string_val';
unset($unset_var);
//defining a class
class sample {
public function __toString() {
return "sample object";
}
}
//getting the resource
$file_handle = fopen(__FILE__, "r");
// array with different values for $input
$inputs = array (
// integer values
/*1*/ 0,
1,
255,
256,
// float values
/*5*/ 10.5,
-20.5,
1.1234e6,
// boolean values
/*11*/ true,
false,
TRUE,
FALSE,
// null values
/*15*/ NULL,
null,
// undefined variable
/*19*/ @$undefined_var,
// unset variable
/*20*/ @$unset_var
);
// loop through with each element
// of the $inputs array to test chr() function
$count = 1;
foreach($inputs as $input) {
echo "<br><br>Iteration: $count<br>";
var_dump( bin2hex(chr($input)) );
$count ++;
}
fclose($file_handle);
//closing the file handle
?>