← Back to Chapters

PHP chr() & ord() Functions

? PHP chr() & ord() Functions

? Quick Overview

The chr() and ord() functions in PHP are used to convert between ASCII values and their corresponding characters. They are commonly used for string manipulation and character-level operations.

⚡ Key Concepts

  • chr() converts an ASCII number into its character representation.
  • ord() returns the ASCII value of the first character in a string.

? Syntax & Theory

  • chr(int $ascii) → character
  • ord(string $char) → integer

? Code Example: chr()

? View Code Example
// Convert ASCII value to character
<?php
$char = chr(65);
echo $char;
?>

? Live Output / Explanation

The output will be A because ASCII value 65 corresponds to the character A.

? Code Example: ord()

? View Code Example
// Convert character to ASCII value
<?php
$ascii = ord("A");
echo $ascii;
?>

? Live Output / Explanation

The output will be 65 because A has an ASCII value of 65.

? Interactive Concept

You can loop through ASCII values (65–90) using chr() to dynamically generate the English alphabet.

? Use Cases

  • Generating characters dynamically in loops
  • Character comparison and encoding logic
  • Simple encryption and decoding logic

✅ Tips & Best Practices

  • Use chr() for ASCII-based character generation.
  • Use ord() to analyze or compare characters.
  • For Unicode characters, prefer multibyte-safe functions.

? Try It Yourself

  • Generate characters from ASCII 97 to 122 using a loop.
  • Calculate the total ASCII value of all characters in a string.
  • Experiment with special characters using both functions.