ord() Function in PHP 8.2, PHP 8.3 & PHP 8.4


The ord() function in PHP returns the ASCII value of the first character of a string. Here are some examples demonstrating its usage in PHP 8. PHP 8.1, PHP 8.2,PHP 8.3,and PHP 8.4.

Basic Examples

<?php
// Get ASCII value of a single character
echo ord('A'); // Output: 65
echo ord('a'); // Output: 97
echo ord('0'); // Output: 48
echo ord(' '); // Output: 32 (space)
echo ord(''); // Output: 226 (for multi-byte characters, returns first byte)
?<

Handling Different Character Cases

<?php
// Difference between uppercase and lowercase
$upperA = ord('A'); // 65
$lowerA = ord('a'); // 97
echo "Difference between 'A' and 'a': " . ($lowerA - $upperA); // Output: 32
?<
Working with Strings
<?php
// Only first character is considered
echo ord("Hello"); // Output: 72 (ASCII for 'H')
// Empty string warning in PHP 8.2
// echo ord(""); // This would generate a warnin
?<

Note About Multibyte Characters

For UTF-8 characters, ord() only returns the value of the first byte. For full Unicode support, consider using mb_ord() from the mbstring extension:

<?phpif (function_exists('mb_ord')) { echo mb_ord('', 'UTF-8'); // Output: 8364 (proper Euro sign code point)} else { echo ord(''); // Output: 226 (just first byte)}

Remember that ord() is a simple function that has been consistent across PHP versions, so these examples will work similarly in PHP 8.2 as they did in earlier versions.