How to usestr_split() and ord() Functions in PHP

Another approach is to use the str_split() function to convert the number to an array of digits and then use ord() to find the ASCII value of each digit .str_split((string)$number) converts the number to a string and then splits it into an array of digits. ord($digit) returns the ASCII value of each digit in the array.

Example: This example shows the conversion of digits into ASCII value by the use of str_split() function.

PHP
<?php

// Given number
$number = 12345;

// Convert the number to an array of digits
$digits = str_split((string)$number);

// Iterate through each digit
foreach ($digits as $digit) {
    
    // Print the ASCII value of each digit
    echo "ASCII value of $digit is: " 
        . ord($digit) . "\n";
}

?>

Output
ASCII value of 1 is: 49
ASCII value of 2 is: 50
ASCII value of 3 is: 51
ASCII value of 4 is: 52
ASCII value of 5 is: 53

PHP Program to Print ASCII Value of all Digits of a Given Number

Given a number, the task is to print ASCII value of all digits of a given number in PHP. ASCII values are often used to represent characters and digits. Sometimes, it’s necessary to find the ASCII value of each digit in a given number, especially when dealing with character encoding or data manipulation.

Table of Content

  • Using String Conversion and ord() Function
  • Using str_split() and ord() Functions
  • Using Mathematical Operations

Similar Reads

Approach 1: Using String Conversion and ord() Function

The basic method to find the ASCII value of each digit in a number is to convert the number to a string and then use the ord() function to get the ASCII value of each character (digit) in the string....

Approach 2: Using str_split() and ord() Functions

Another approach is to use the str_split() function to convert the number to an array of digits and then use ord() to find the ASCII value of each digit .str_split((string)$number) converts the number to a string and then splits it into an array of digits. ord($digit) returns the ASCII value of each digit in the array....

Approach 3: Using Mathematical Operations

If you want to avoid converting the number to a string, you can use mathematical operations to extract each digit and then find its ASCII value. In this approach, The while loop iterates until the number becomes 0. $number % 10 extracts the last digit of the number. ord((string)$digit) converts the digit to a string and then gets its ASCII value. (int)($number / 10) removes the last digit from the number by dividing it by 10 and converting it to an integer....

Contact Us