Skip to main content

Loop Through All Characters of a String in PHP

PHP makes it easy to loop through all the characters in a string. This can come in handy if you need to do something with each character in a string.

To loop through all characters of a string in PHP, we can use the str_split function. This function splits a string into an array of smaller strings, each of which is a single character. Then we can then loop through this array using a foreach loop. In each iteration of the loop, we can print or manipulate the character as needed. 

$string = 'PHP is a versatile scripting language that can be used for web development, system administration, and even game development.';
$chars_array = str_split($string);
foreach ($chars_array as $key => $char) {
	echo $char.'<br>';

Or we can use for loop with the length of the string as count and iterate through each character.

$string = 'PHP is an open source language, which means it is free to use and distribute.';
for($i = 0; $i < strlen($string); $i++){
  echo $string[$i];

By continuing to use the site, you agree to the use of cookies.