Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - ord() Function



The PHP ord() function is used to convert the first character (or byte) of a string to an integer value representing its ASCII (or extended ASCII) value, which is an unsigned integer between 0 and 255.

ASCII stands for "American Standard Code" for Information Interchange. It is a character encoding standard used in computers and electronic devices to represent text.

Syntax

Following is the syntax of the PHP ord() function −

ord(string $str): int

Parameters

This function accepts a single parameter, which is described below −

  • str − It is a character set.

Return value

This function returns an integer between 0 to 255.

Example 1

The following is a basic example of the PHP ord() function −

<?php
   $str = "T";
   echo "The given charset: $str";
   echo "\nAn ascii value is: ";
   #using ord() functio
   echo ord($str);
?>

Output

Following is the output of the above program −

The given charset: T
An ascii value is: 84

Example 2

Following is another example of the PHP ord() function. We use this function to convert the first byte of a string to an integer value between 0 to 255

<?php
   $str = "Hello from TP";
   echo "The given charset: $str";
   echo "\nAn ASCII value is: ";
   #using ord() functio
   echo ord($str);
?>

Output

After executing the above program, the following output will be displayed −

The given charset: Hello from TP
An ASCII value is: 72

Example 3

In the example below, we use this function to retrieve an integer value of the first character (or byte) of a string between 0 to 255, and then compare it to determine if it is the number 10, which corresponds to the line feed character −

<?php
   $str = "\nHello World";
   echo "The given charset: $str";
   $ascii = ord($str);
   if($ascii == 10){
      echo "\nThe first character is line feed";
   }
?>

Output

The above program produces the following output −

Hello World
The first character is line feed
php_function_reference.htm
Advertisements