codescracker


php

PHP foreach Loop



« Previous Tutorial Next Tutorial »


The foreach loop only works on arrays, used to loop through each key/value pair in an array. Here is the general form to use foreach loop in PHP:

foreach ($array as $value)
{
    code to be executed here;
}

For every loop iteration, the current array element's value is assigned to the variable $value and then the array pointer is moved by one, until it reaches to the last element of the array. Here is another example, also uses foreach loop in PHP:

<html>
<body>
<?php
	$googlers = array("Alok", "Gaurav", "Anish", "Saurabh");
	foreach ($googlers as $value)
	{
		echo $value;
		echo "<br/>";
	}
?>
</body>
</html>

The above PHP script will produce following output:

PHP foreach loop

Below is one more example demonstrating foreach loop in PHP.

<!DOCTYPE html>
<html>
<head>
	<title>PHP foreach Loop Example</title>
</head>
<body>
<?php
	$tutorial = ['C++', 'Java', 'C', 'PHP', 'JavaScript', 'Everything'];
	foreach($tutorial as $value)
	{
		echo "I just love to read ".$value." on CodesCracker";
		echo "<br/>";
	}
?>
</body>
</html>

Here is the sample output produced by the above foreach loop example code in PHP.

foreach loop in php

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test