How to use foreach loop for a string in PHP?

In this tutorial, I am going to show you how to use foreach loop for a string in PHP?

If you have a string variable, then it will need to be converted into an array first. The code below demonstrates how to use foreach loop for a string in PHP:

<?php

	//convert the string into array
	$string_array = str_split("foreach");
    
	
	//loop through the array
	foreach ($string_array as $character) {
		
		//print the character
		echo $character .'<br/>';
	}
?>

Output:

f
o
r
e
a
c
h

In the above example, by using str_split(), we convert string to an array. After that loop through the array and print each character.

The str_split() function can’t handle Unicode strings. So, use mb_str_split() instead. If you are getting the error “The mbstring extension is missing. Please check your PHP configuration” you can read this article.

How to string concatenation using foreach loop?

Suppose you have a string of comma-separated keywords and you want to make a list item from it. So you can easily generate list items using foreach loop. Let’s check an example:

<?php

	$string = 'php,jquery,html,css';
	$list = "";
	$keywords_array = explode(',', $string);

	$list .= "<ol>";
	
	foreach ($keywords_array as $keyword){
		
		$list .= "<li>$keyword</li>";
	}
	
	$list .= "</ol>";

	echo $list;
?>

Output:

  1. php
  2. jquery
  3. html
  4. css

How to iterate over each line using foreach loop?

Suppose you need to iterate over each line and get the value, you can use the below code.

<?php

	$string = 
	'How to use 
foreach loop for
a string in PHP?';
	
	foreach(preg_split("/((\r?\n)|(\r\n?))/", $string) as $line){
		echo $line .'<br/>';
	} 
	
	
?>

Output:

How to use
foreach loop for
a string in PHP?

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment