Open In App

PHP Program to Convert String to ASCII Value

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




<?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

  • The array_map() function is used to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
  • The PHP ord() function returns the ASCII value of the first character of a string.
  • The str_split() function is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.

Syntax:

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

PHP




<?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
)






Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads