How to use str_split() function and foreach Loop In PHP
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
// 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
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
Contact Us