ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

PHP Code in Foreach Loop and For Loop and the Difference Between

Updated on February 22, 2013

PHP Code, Sample PHP scripts, PHP code examples on foreach loop and for loop.

You might be curious. What is the difference between for loop and foreach loop? Sure, for loop is a common thing in programming but foreach loop is new is it? The foreach loop in PHP is designed to loop through the array. A powerful built-in function indeed. To know more about for loop and foreach loop in php, please study the example code below and the example outputs.

Note: If you do not know yet on how to run a php file on your browser, then please take a look on the link below. It offers steps on how test and run php file on your own computer.

How to run a PHP file on your own Browser Using Notepad++ and XAAMP

Below is the PHP Sample Codes

Sample PHP Code for Foreach Loop

<?php
	$array = array(11, 12, 13, 14, 15, 16, 17, 18,19 ,20);
	$sum = 0;
	
	foreach($array as $num)
	{
		echo $sum. " + ". $num. " is equal to: ";
		$sum = $sum + $num;
		echo $sum."<br />";
		
	}
	echo "<br />";
	echo "The Total sum of the numbers 11 to 20 is: ". $sum;
?>

Sample Output for Foreach Loop

PHP Code Example for For Loop

<?php
	
	$sum=0;
	$product=1;
	
	echo "The sum of numbers from 1 to 10 is: ";
	for($num = 1; $num<=10; $num++)
	{	
		$sum = $sum + $num;
	}
	echo $sum. "<br />";
	
	
	echo "The Product of numbers from 1 to 10 is: ";
	for($num = 1; $num<=10; $num++)
	{	
		$product = $product * $num;
	}
	echo $product. "<br />";
	
	
?>

Sample Output for For Loop

A General Guide for Beginners

If you want to run the code above better save the file with foreachloop.php and forloop.php

Requirements to Run the Code

1. Installed XAAMP and Notepad++

2. The Apache and My SQL are running on XAAMP interface.

How to Save the Code

1. Open Xaamp folder and htdocs folder.

2. Save the file on the htdocs folder with the filename indicated above.

How to Run the Code on Your Browser

1. Just open 2 new tabs. and type on the address bar number 1 this: localhost/foreachloop.php

2.Address bar numbers 2 type this: localhost/forloop.php

Comments

    0 of 8192 characters used
    Post Comment

    • dwachira profile image

      [ Danson Wachira ] 4 years ago from Nairobi, Kenya

      This is a useful article especially for beginners in Web programming, i like the example and its illustrations. Voted up and useful.

    • aisha91 profile image
      Author

      Rasna Aisha 4 years ago from Manila, Philippines

      Thank You dwachira for your appreciation and for voting it up :D

    • aisha91 profile image
      Author

      Rasna Aisha 4 years ago from Manila, Philippines

      Thank You dwachira for your appreciation and for voting it up :D

    Click to Rate This Article