Backend Development 4 min read

Using PHP ord() Function to Retrieve ASCII Values of Characters

This article explains PHP's built-in ord() function, detailing its syntax, parameters, return values, and usage examples—including single character, string, and looped character processing—while noting its limitations with multibyte characters and providing guidance on handling such cases.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP ord() Function to Retrieve ASCII Values of Characters

PHP is a widely used open‑source scripting language for web development. The built‑in ord() function returns the ASCII value of the first character of a given string.

Syntax of ord()

int ord ( string $string )

Parameter

string : The string whose first character's ASCII value is to be obtained.

Return value

The function returns the ASCII value of the first character of the string.

The ord() function is primarily used to convert a character to its corresponding ASCII code. ASCII is a standard encoding where each character is assigned a unique integer.

Examples

Example 1: Get ASCII value of a character

echo ord('A'); // outputs 65<br/>echo ord('B'); // outputs 66<br/>echo ord('a'); // outputs 97<br/>echo ord('b'); // outputs 98

Example 2: Get ASCII value of the first character of a string

echo ord('Hello'); // outputs 72<br/>echo ord('World'); // outputs 87

Example 3: Loop through a string to get ASCII values of each character

$str = 'Hello World';<br/>for ($i = 0; $i < strlen($str); $i++) {<br/>    echo ord($str[$i]) . ' ';<br/>}<br/>// outputs 72 101 108 108 111 32 87 111 114 108 100

The function only handles single‑byte characters; for multibyte characters it returns the ASCII value of the first byte. Use mb_ord() for multibyte support.

Note that ord() returns 0 for an empty string or a non‑string argument, so ensure the argument is a valid string before calling.

Summary

The ord() function is convenient for obtaining ASCII values of single‑byte characters, but has limitations with multibyte characters and empty inputs.

String()ASCIIordphp-functions
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.