Master PHP’s ord() Function: Convert Characters to ASCII Values
This article explains how PHP's built‑in ord() function returns the ASCII code of a string's first character, details its syntax and parameters, shows multiple usage examples—including loops and handling of multibyte characters—and highlights important limitations and alternatives.
PHP is a widely used open‑source scripting language for web development. The built‑in function ord() returns the ASCII value of the first character of a given string.
Syntax of ord()
int ord ( string $string )Parameter description:
string: The string whose first character’s ASCII value is to be obtained.
Return value:
Returns the ASCII value of the first character of the string.
The ord() function is mainly used to convert a character to its ASCII code. ASCII (American Standard Code for Information Interchange) assigns a unique integer to each character.
Examples of using ord()
Example 1: Get ASCII value of a character
echo ord('A'); // outputs 65
echo ord('B'); // outputs 66
echo ord('a'); // outputs 97
echo ord('b'); // outputs 98Example 2: Get ASCII value of the first character of a string
echo ord('Hello'); // outputs 72
echo ord('World'); // outputs 87Example 3: Loop through a string to get ASCII values of each character
$str = 'Hello World';
for ($i = 0; $i < strlen($str); $i++) {
echo ord($str[$i]) . ' ';
}
// outputs 72 101 108 108 111 32 87 111 114 108 100The ord() function has limitations with non‑ASCII or multibyte characters; it only handles single‑byte characters and returns the ASCII value of the first byte. For multibyte strings, use mb_ord() instead.
Note that ord() returns 0 for an empty string or when the argument is not a string, so ensure the parameter is a valid string before calling it.
Summary
The ord() function is a built‑in PHP function that retrieves the ASCII value of the first character of a string. It works well for single‑byte characters, but has limitations with multibyte characters; for those, consider using mb_ord().
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
