How to Iterate Over Characters of a String in PHP ?

This article will show you how to iterate over characters of string in PHP. It means how to loop through an array of characters in a string. There are two methods to iterate over the character of a string, these are:

Table of Content

  • Using str_split() function and foreach Loop
  • Using for Loop
  • Using mb_substr() with while loop

Using str_split() function and foreach Loop

The str_split() function converts the given string into an array and then uses foreach loop to iterate over an array of elements.

Syntax:

$chars = str_split($str);
foreach ($chars as $char) {
    echo $char . "\n";
}

Example: This example uses str_split() function and foreach Loop to iterate over characters of string.

PHP
<?php

// Declarre an array
$str = "w3wiki";

$chars = str_split($str);

foreach ($chars as $char) {
    echo $char . "\n";
}

?>

Output
G
e
e
k
s
f
o
r
G
e
e
k
s

Using for Loop

The for loop is used to iterate the array elements and execute the block. The for loop contains the initialization expression, test condition, and update expression (expression for increment or decrement).

Syntax:

for ($i = 0; $i < strlen($str); $i++) {
    echo $str[$i] . "\n";
}

Example: This example uses for loop to iterate over characters of string.

PHP
&lt;?php

// Declarre an array
$str = &quot;w3wiki&quot;;

for ($i = 0; $i &lt; strlen($str); $i++) {
    echo $str[$i] . &quot;\n&quot;;
}

?&gt;

Output
G
e
e
k
s
f
o
r
G
e
e
k
s

Using mb_substr() with while loop

Using mb_substr() with a while loop in PHP involves determining the string length with mb_strlen() and iterating through each character using mb_substr(), ensuring correct handling of multi-byte characters for accurate iteration.

Syntax:

while ($i < $len) {
$char = mb_substr($str, $i, 1, 'UTF-8');
echo $char . "\n";
$i++;
}

Example:

PHP
<?php

$str = "w3wiki";
$len = mb_strlen($str, 'UTF-8');
$i = 0;

while ($i < $len) {
    $char = mb_substr($str, $i, 1, 'UTF-8');
    echo $char . "\n";
    $i++;
}

?>

Output:

G
e
e
k
s
f
o
r
G
e
e
k
s

Contact Us