124 of 410 menu

The chr Function

The chr function finds a character by its ASCII code.

Syntax

chr(int $codepoint): string

Example

Let's output the character that has the code 97:

<?php echo chr(97); ?>

Code execution result:

'a'

Example . Application

Let's output a random lowercase letter of the Latin alphabet. To do this, let's look at the ASCII table and see that lowercase Latin letters have codes from 97 to 122. Therefore, let's generate a random number in this range using mt_rand and pass the result to chr:

<?php echo chr(mt_rand(97, 122)); ?>

Example . Application

Now let's form a random string of 6 lowercase Latin letters. For this, we will repeat the operation described in the previous example 6 times in a loop:

<?php $str = ''; for ($i = 1; $i <= 6; $i++) { $str .= chr(mt_rand(97, 122)); } echo $str; ?>

Example . Application

Uppercase Latin letters have the range 65-90, and lowercase ones - 97-122. That is, there is a gap between them. Let's get a random character, either a lowercase or uppercase Latin letter. To do this, using range, form 2 arrays: the first with numbers from 65 to 90, and the second with numbers from 97 to 122. Merge them together using array_merge and then output a random element of this array using array_rand:

<?php $codes = array_merge(range(65, 90), range(97, 122)); echo chr($codes[array_rand($codes)]); ?>

See Also

  • the ord function,
    which returns the character code
byenru