Open In App

PHP Program to Convert String to ASCII Value

Given a String the task is to convert the given string into ASCII code using PHP. ASCII is the American Standard Code for Information Interchange, which is a widely used standard for encoding characters in computers and digital communication systems.

There are two methods to convert a given String into ASCII code, these are as follows:



Using ord() Function and for() Loop

The PHP ord() function returns the ASCII value of the first character of a string. This function takes a character string as a parameter and returns the ASCII value of the first character of this string.



Syntax:

int ord( $string )

Example:




<?php
 
$str = "GFG";
$asciiArr = [];
 
for ($i = 0; $i < strlen($str); $i++) {
       $asciiArr[$i] = ord($str[$i]);
}
 
print_r($asciiArr);
 
?>

Output
Array
(
    [0] => 71
    [1] => 70
    [2] => 71
)




Using array_map(), ord() and str_split() Methods

Syntax:

array_map(function($char) {
return ord($char);
}, str_split($str));




<?php
 
$str = "GFG";
 
$asciiArr = array_map(function($char) {
    return ord($char);
}, str_split($str));
 
print_r($asciiArr);
 
?>

Output
Array
(
    [0] => 71
    [1] => 70
    [2] => 71
)





Article Tags :