In this PHP tutorial, you shall learn how to loop through characters in a given string using str_split() function and foreach statement, or use the index of characters in the string with a For loop, with example programs.
PHP – Loop through Characters in String
To iterate over each character in a string, there are following two approaches.
1. Using str_split() and foreach
- Take a string.
- Split the string into an array of characters using str_split() function.
- Use a looping statement like for loop or while loop, to iterate over each of the element (character) in the array.
2. Using index and for loop
- Take a string.
- Initialize index to 0.
- Define for loop that iterates when the index is less than string length.
- Access character using string and index.
Examples
1. For each character in string using str_split() and foreach
In this example, we will take a string, say “apple”, and iterate over each character of the string using str_split() function and foreach statement.
PHP Program
<?php
$str = "apple";
$chars = str_split($str);
foreach ($chars as $char) {
echo $char;
echo "<br>";
}
?>
Program Output
2. Iterate over characters in String using Index and For Loop
In this example, we will take a string, say “apple”, and iterate over each character of the string using index, that increments for each iteration, and for loop statement.
PHP Program
<?php
$str = "apple";
$length = strlen($str);
for ($index = 0; $index < $length; $index++) {
echo $str[$index];
echo "<br>";
}
?>
Program Output
Conclusion
In this PHP Tutorial, we learned how to iterate or loop for each character in a string, using different ways in PHP.