PHP Function Reference

PHP ord() Function



The PHP ord() function returns the ASCII value of the first character of the specified string.

This function complements chr() function.

Syntax

ord(string)

Parameters

string Required. Specify the string to get the ASCII value of first character of the string.

Return Value

Returns the ASCII value of the first character of the specified string.

Example: ord() example

In the example below, ord() function returns the ASCII value of the first character of the specified string.

<?php
$MyString = "Apple";

echo ord($MyString)."\n";
?>

The output of the above code will be:

65

Example: getting the individual bytes of a UTF-8 string

Consider the example below where this function is used to get the individual bytes of a given UTF-8 string.

<?php
//a UTF-8 string
$str = "😎";

//getting individual bytes
for ($pos=0; $pos < strlen($str); $pos++) {
 $byte = substr($str, $pos);
 echo 'Byte '. $pos .' of $str has value '.ord($byte)."\n";
}
?>

The output of the above code will be:

Byte 0 of $str has value 240
Byte 1 of $str has value 159
Byte 2 of $str has value 152
Byte 3 of $str has value 142

❮ PHP String Reference