PHP ord() Function

PHP

PHP ord() - Get ASCII Code

SEO Description: Learn PHP ord() function. Get the ASCII code of the first character of a string.

Introduction

The ord() function in PHP is a powerful and straightforward tool for converting the first character of a string into its corresponding ASCII value (also known as the character code). This function is widely used in string manipulation, encoding, encryption, and character analysis tasks.

Understanding how to work with ASCII codes can help programmers analyze or transform string data efficiently by dealing with the numerical representations of characters. In this tutorial, weโ€™ll explore everything you need to know about the PHP ord() functionโ€”how to set it up, practical examples, best practices, common mistakes to avoid, and related interview questions.

Prerequisites

  • Basic understanding of PHP programming.
  • Familiarity with string operations and ASCII encoding concepts.
  • PHP environment ready for testing code snippets (e.g., XAMPP, WAMP, or a live server).
  • PHP 5 or higher (recommended, generally all modern PHP versions support ord()).

Setup Steps

No special setup is required to use the ord() function โ€” it is a built-in PHP function available by default.

Just make sure you have a functioning PHP environment and a script file to test your code. For example, create a file named test_ord.php:

<?php
// Test script to demonstrate ord() usage
$str = "A";
echo ord($str);
?>

Run the above script using your PHP interpreter or server:

php test_ord.php

You will get the ASCII value of uppercase 'A' as output, which is 65.

Understanding PHP ord() Function

Function signature: int ord(string $string)

Description:

  • ord() takes a string as input and returns the ASCII value of the first character of that string.
  • If the input string is empty, it returns 0.
  • If the first character is multibyte (non-ASCII), it only processes the first byte of that character, which may produce unexpected values for non-ASCII characters.

Examples

Example 1: Basic usage with single character

<?php
$char = "C";
echo "ASCII code of '$char': " . ord($char);  // Output: 67
?>

Example 2: Using ord() with a string (multiple characters)

<?php
$str = "Hello";
echo "ASCII code of first character '" . $str[0] . "': " . ord($str);  // Output: 72
?>

Example 3: Using ord() with empty string

<?php
$empty = "";
echo "ASCII code: " . ord($empty);  // Output: 0
?>

Example 4: ASCII values of numbers and symbols

<?php
echo ord("1");   // Output: 49
echo "\n";
echo ord("#");   // Output: 35
?>

Example 5: Handling multibyte characters (UTF-8)

Note that ord() may not behave as expected with multibyte characters:

<?php
$char = "รฑ"; // UTF-8 multibyte character
echo ord($char);  // Output: 195 (first byte of UTF-8 encoding)
?>

To properly handle multibyte characters, use PHP's mb_ord() function (available in PHP 7.2+).

Best Practices

  • Always ensure the input string is not empty before calling ord() to avoid confusion with output 0.
  • Be cautious using ord() with multibyte (non-ASCII) characters. Consider using mb_ord() for UTF-8 strings.
  • Use ord() only when you need the ASCII value of the first character. If you need all charactersโ€™ ASCII codes, iterate over the string or use alternative approaches.
  • If working with data from unknown encodings, convert strings to ASCII-compatible or single-byte encodings before using ord().

Common Mistakes

  • Passing an empty string expecting an error โ€” ord('') returns 0 silently.
  • Using ord() on multibyte characters and assuming the result corresponds to the full character code.
  • Trying to retrieve ASCII codes for all characters without looping through the string.
  • Mixing up chr() and ord() โ€” remember ord() converts char to ASCII; chr() converts ASCII to char.

Interview Questions on PHP ord() Function

Junior Level Questions

  1. What does PHP's ord() function do?
    Answer: It returns the ASCII value of the first character of a string.
  2. What is the output of ord("A")?
    Answer: 65
  3. What happens if you pass an empty string to ord()?
    Answer: It returns 0.
  4. Can ord() work with multibyte characters like 'รฑ'?
    Answer: No, it processes only the first byte; for multibyte characters use mb_ord().
  5. Which data type does ord() return?
    Answer: Integer representing the ASCII value.

Mid-Level Questions

  1. How would you get the ASCII values of all characters in a string using ord()?
    Answer: Loop through each character of the string and call ord() on each.
  2. Explain the difference between ord() and chr() in PHP.
    Answer: ord() converts a character to its ASCII code; chr() converts an ASCII code to a character.
  3. What alternative function should be used for UTF-8 strings instead of ord()?
    Answer: Use mb_ord() for multibyte (UTF-8) characters.
  4. Is it safe to assume ord() always returns the correct Unicode code point?
    Answer: No, it only returns the ASCII value of the first byte, not the full Unicode code point.
  5. If a variable contains a string longer than one character, how does ord() behave?
    Answer: It returns the ASCII value of only the first character.

Senior Level Questions

  1. How would you implement a function to convert a UTF-8 string to an array of Unicode code points, considering ord() limitations?
    Answer: Use mb_convert_encoding and mb_ord() in a loop to extract each code point properly.
  2. Explain a scenario where using ord() could lead to security vulnerabilities.
    Answer: Using ord() on untrusted multibyte input may misinterpret character codes, potentially bypassing character-based filters.
  3. How can you optimize retrieval of ASCII codes for large strings in PHP?
    Answer: Use loops with ord() or efficient binary operations, or leverage PHP's extension libraries for bulk conversion.
  4. Discuss why ord() returns values based on bytes and how it relates to PHP string encoding models.
    Answer: PHP strings are byte sequences; ord() returns the integer value of the first byte, not character, reflecting PHP's byte-oriented string handling.
  5. How would you handle mixed encoding data using ord() safely?
    Answer: Normalize all input strings to a consistent encoding (e.g., UTF-8), then process with mb_ord() instead of ord().

FAQ

Q1: What value does ord() return if the input string is empty?

A: It returns 0 without any warning.

Q2: Does ord() support Unicode characters?

A: No, ord() only returns the ASCII value of the first byte. For Unicode, use mb_ord().

Q3: How to get ASCII codes for every character in a string?

A: Loop over the stringโ€™s characters and call ord() on each one.

Q4: What is the difference between ord() and chr()?

A: ord() converts a character to an ASCII value; chr() converts an ASCII value back to a character.

Q5: Can ord() cause errors if given invalid input?

A: No, it returns 0 for empty strings and returns an integer otherwise. However, unexpected results may occur with multibyte strings.

Conclusion

The PHP ord() function is a simple yet essential tool for extracting ASCII codes from characters in strings. It is invaluable for tasks involving character code manipulation, encoding, and basic text analysis. However, understanding its byte-based nature and limitations with multibyte characters is critical to avoid pitfalls.

For modern applications dealing with UTF-8 or multibyte data, combining ord() with other PHP extensions or switching to mb_ord() will ensure proper and reliable results.

With this tutorial, you now have a comprehensive understanding of how to use ord() in PHP, along with practical insights to implement it safely and effectively.