Code has been added to clipboard!

PHP for Loop: How Is It Different from PHP foreach Loop

Reading time 3 min
Published Aug 8, 2017
Updated Sep 24, 2019

After learning the concept of PHP loops and getting to know their simplest types, you should try the more complex ones - PHP for and PHP foreach loops.

PHP foreach loops have a particular purpose. They are meant to be used with the more complex types of PHP variables - arrays and objects. Using foreach PHP code blocks will be run repeatedly with their every element in a row.

Now, PHP for loop is meant to execute portions of code multiple times. You can specify how many times the execution will occur. Therefore, this loop is best-suited in situations when you are confident of the times the block of code needs to run. No conditions matter: in any case, a loop runs a specified number of times.

PHP for Loop and foreach: Main Tips

  • Loops run a selected block of code multiple times.
  • PHP for loop should be used when you know exactly how many times it should be looped.
  • PHP foreach loop only works with arrays and objects. It runs with their every element.

for() Defined

The for loop PHP script runs a block of code multiple times repeatedly. The number of times has to be specified in advance.

It might become clearer if you analyze an example. You will notice that the code below prints out the numbers from 0 to 10:

Example
<?php 
  for ($x = 0; $x <= 10; $x++) 
  {  	    
     echo "The number is: $x <br>";
  } 
?>

Correct Syntax

For PHP for loop to function properly, you must keep the correct syntax in mind:

for (init; test; increment)

Parameters

Understanding what each element stands for makes it easier to commit the syntax rules to your memory. Let's break them down to understand how to use PHP for loop even better:

  • init: Specifies the start value.
  • test: Checks the specified condition with every loop. If it is true, the loop continues. If it proves False, the loop stops.
  • increment: Changes the value of iterator with every loop.

foreach() Explained

The PHP foreach loop functions in a similar way as the regular PHPfor loop, but only works with arrays and objects. If you try to use it on other types of variables, an error will occur. Different rules for syntax apply as well.

With every foreach PHP loop, the $value parameter changes to a new value. During a PHP loop through array or an object, $value obtains every element's value one by one until the array ends.

Look at the example below. In it, PHP foreach loop is used to display every element in the $animals array:

Example
<?php 
  $animals = array("rabbit", "cat", "bmw", "lama");
  foreach ($animals as $value) 
  {    
     echo "$value <br>";
  }
?>

Syntax

If you wish for your PHP foreach loop to execute as it should, you must follow the syntax requirements. Take a look:

foreach (array_expression as $value)

PHP for Loop and foreach: Summary

  • Loops are meant to ease running a certain portion of code repetitively.
  • When using for loop, you should know in advance how many times you want the code to be looped.
  • foreach loop only works with complex variables (arrays and objects). It works with their every element seperately.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()