- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
PHP Code in Foreach Loop and For Loop and the Difference Between
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
Other PHP Sample Codes and Tutorials
- How to become a PHP Developer: Learn and Earn
- Steps on How to Program in PHP: A Beginner's Guide on PHP Programming-Part 1
- How to run PHP Code or PHP Scripts and See the Result on Your Browser
- PHP Sample Codes On Function:How to make Function in PHP
- HTML Basics: Learn The Basics of HTML and Create Your Own Webpage on Your Browser
- PHP Code Example on Associative Array and Multidimensional Array
- PHP Code Example on Do-while Loop
- PHP Code Example on Numeric Array
- PHP Code Example on While Loop
- PHP Code Example on Switch Statement
- PHP Code Example on if else-if Statement
- PHP Code Example for if-else Statement
- PHP code Example for if statement