Skip to content
Related Articles

Related Articles

How to read each character of a string in PHP ?

Improve Article
Save Article
  • Last Updated : 21 Oct, 2021
Improve Article
Save Article

A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. 

Approach 1: Using str_split() method – The str_split() method is used to split the specified string variable into an array of values, each of which is mapped to an index value beginning with 0. This method converts the input string into an array.

str_split(str)

 PHP foreach loop iteration can then be done over the array values, each of which element belongs to a character of the string. The values are then printed with a space in between each. 

Example:

PHP




<?php
    
// Declaring string variable 
$str = "Hi!GFG User.";
  
echo("Original string : ");
echo($str . "</br>");
  
$array = str_split($str);
echo("Characters : ");
  
foreach($array as $val){
    echo($val . " ");
}
  
?>


Output:

Original string : Hi!GFG User.
Characters : H i ! G F G U s e r .

Approach 2: Using strlen() method – The strlen() method is used to compute the length of the specified string in PHP. A for loop iteration is applied using the length of the string, and the ith index character is printed each time. The time complexity is the same as the previous method. However, no extra space is required to store the string in the form of the array object. 

strlen(str)

Example:

PHP




<?php
    
// Declaring string variable 
$str = "Hi!GFG User.";
  
echo("Original string : ");
echo($str."</br>");
echo("Characters : ");
  
// Iterating over the string 
$len = strlen($str);
  
for ($i = 0; $i < $len; $i++){
    echo ($str[$i]." ");
}
  
?>


Output:

Original string : Hi!GFG User.
Characters : H i ! G F G U s e r .

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!