How to Iterate Over Characters of a String in PHP ?
Last Updated :
16 Nov, 2023
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:
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
$str = "GeeksforGeeks" ;
$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
<?php
$str = "GeeksforGeeks" ;
for ( $i = 0; $i < strlen ( $str ); $i ++) {
echo $str [ $i ] . "\n" ;
}
?>
|
Output
G
e
e
k
s
f
o
r
G
e
e
k
s
Share your thoughts in the comments
Please Login to comment...