- PHP Tutorial
- PHP - Home
- PHP - Introduction
- PHP - Installation
- PHP - History
- PHP - Features
- PHP - Syntax
- PHP - Hello World
- PHP - Comments
- PHP - Variables
- PHP - Echo/Print
- PHP - var_dump
- PHP - $ and $$ Variables
- PHP - Constants
- PHP - Magic Constants
- PHP - Data Types
- PHP - Type Casting
- PHP - Type Juggling
- PHP - Strings
- PHP - Boolean
- PHP - Integers
- PHP - Files & I/O
- PHP - Maths Functions
- PHP - Heredoc & Nowdoc
- PHP - Compound Types
- PHP - File Include
- PHP - Date & Time
- PHP - Scalar Type Declarations
- PHP - Return Type Declarations
- PHP Operators
- PHP - Operators
- PHP - Arithmatic Operators
- PHP - Comparison Operators
- PHP - Logical Operators
- PHP - Assignment Operators
- PHP - String Operators
- PHP - Array Operators
- PHP - Conditional Operators
- PHP - Spread Operator
- PHP - Null Coalescing Operator
- PHP - Spaceship Operator
- PHP Control Statements
- PHP - Decision Making
- PHP - If…Else Statement
- PHP - Switch Statement
- PHP - Loop Types
- PHP - For Loop
- PHP - Foreach Loop
- PHP - While Loop
- PHP - Do…While Loop
- PHP - Break Statement
- PHP - Continue Statement
- PHP Arrays
- PHP - Arrays
- PHP - Indexed Array
- PHP - Associative Array
- PHP - Multidimensional Array
- PHP - Array Functions
- PHP - Constant Arrays
- PHP Functions
- PHP - Functions
- PHP - Function Parameters
- PHP - Call by value
- PHP - Call by Reference
- PHP - Default Arguments
- PHP - Named Arguments
- PHP - Variable Arguments
- PHP - Returning Values
- PHP - Passing Functions
- PHP - Recursive Functions
- PHP - Type Hints
- PHP - Variable Scope
- PHP - Strict Typing
- PHP - Anonymous Functions
- PHP - Arrow Functions
- PHP - Variable Functions
- PHP - Local Variables
- PHP - Global Variables
- PHP Superglobals
- PHP - Superglobals
- PHP - $GLOBALS
- PHP - $_SERVER
- PHP - $_REQUEST
- PHP - $_POST
- PHP - $_GET
- PHP - $_FILES
- PHP - $_ENV
- PHP - $_COOKIE
- PHP - $_SESSION
- PHP File Handling
- PHP - File Handling
- PHP - Open File
- PHP - Read File
- PHP - Write File
- PHP - File Existence
- PHP - Download File
- PHP - Copy File
- PHP - Append File
- PHP - Delete File
- PHP - Handle CSV File
- PHP - File Permissions
- PHP - Create Directory
- PHP - Listing Files
- Object Oriented PHP
- PHP - Object Oriented Programming
- PHP - Classes and Objects
- PHP - Constructor and Destructor
- PHP - Access Modifiers
- PHP - Inheritance
- PHP - Class Constants
- PHP - Abstract Classes
- PHP - Interfaces
- PHP - Traits
- PHP - Static Methods
- PHP - Static Properties
- PHP - Namespaces
- PHP - Object Iteration
- PHP - Encapsulation
- PHP - Final Keyword
- PHP - Overloading
- PHP - Cloning Objects
- PHP - Anonymous Classes
- PHP Web Development
- PHP - Web Concepts
- PHP - Form Handling
- PHP - Form Validation
- PHP - Form Email/URL
- PHP - Complete Form
- PHP - File Inclusion
- PHP - GET & POST
- PHP - File Uploading
- PHP - Cookies
- PHP - Sessions
- PHP - Session Options
- PHP - Sending Emails
- PHP - Sanitize Input
- PHP - Post-Redirect-Get (PRG)
- PHP - Flash Messages
- PHP AJAX
- PHP - AJAX Introduction
- PHP - AJAX Search
- PHP - AJAX XML Parser
- PHP - AJAX Auto Complete Search
- PHP - AJAX RSS Feed Example
- PHP XML
- PHP - XML Introduction
- PHP - Simple XML Parser
- PHP - SAX Parser Example
- PHP - DOM Parser Example
- PHP Login Example
- PHP - Login Example
- PHP - Facebook Login
- PHP - Paypal Integration
- PHP - MySQL Login
- PHP Advanced
- PHP - MySQL
- PHP.INI File Configuration
- PHP - Array Destructuring
- PHP - Coding Standard
- PHP - Regular Expression
- PHP - Error Handling
- PHP - Try…Catch
- PHP - Bugs Debugging
- PHP - For C Developers
- PHP - For PERL Developers
- PHP - Frameworks
- PHP - Core PHP vs Frame Works
- PHP - Design Patterns
- PHP - Filters
- PHP - JSON
- PHP - Exceptions
- PHP - Special Types
- PHP - Hashing
- PHP - Encryption
- PHP - is_null() Function
- PHP - System Calls
- PHP - HTTP Authentication
- PHP - Swapping Variables
- PHP - Closure::call()
- PHP - Filtered unserialize()
- PHP - IntlChar
- PHP - CSPRNG
- PHP - Expectations
- PHP - Use Statement
- PHP - Integer Division
- PHP - Deprecated Features
- PHP - Removed Extensions & SAPIs
- PHP - PEAR
- PHP - CSRF
- PHP - FastCGI Process
- PHP - PDO Extension
- PHP - Built-In Functions
- PHP Useful Resources
- PHP - Questions & Answers
- PHP - Quick Guide
- PHP - Useful Resources
- PHP - Discussion
PHP - Foreach Loop
The foreach construct in PHP is specially meant for iterating over arrays. If you try to use it on a variable with a different data type, PHP raises an error.
The foreach loop in PHP can be used with indexed array as well as associative array. There are two types of usage syntaxes available −
foreach (array as $value) { statements }
The above method is useful when you want to iterate an indexed array. The syntax below is more suitable for associative arrays.
foreach (array as $key => $value) { statements }
However, both these approaches work well with indexed array, because the index of an item in the array also acts as the key.
Using "foreach" Loop with an Indexed Array
The first type of syntax above shows a parenthesis in front of the foreach keyword. The name of the array to be traversed is then followed by the "as" keyword and then a variable.
When the fist iteration starts, the first element in the array is assigned to the variable. After the looping block is over, the variable takes the value of the next element and repeats the statements in the loop body till the elements in the array are exhausted.
A typical use of foreach loop is as follows −
<?php $arr = array(10, 20, 30, 40, 50); foreach ($arr as $val) { echo "$val \n"; } ?>
Example
PHP provides a very useful function in array_search() which returns the key of a given value. Since the index itself is the key in an indexed array, the array_search() for each $val returns the zero based index of each value. The following code demonstrates how it works −
<?php $arr = array(10, 20, 30, 40, 50); foreach ($arr as $val) { $index = array_search($val, $arr); echo "Element at index $index is $val \n"; } ?>
It will produce the following output −
Element at index 0 is 10 Element at index 1 is 20 Element at index 2 is 30 Element at index 3 is 40 Element at index 4 is 50
Example
The second variation of foreach syntax unpacks each element in the array into two variables: one for the key and one for value.
Since the index itself acts as the key in case of an indexed array, the $k variable successively takes the incrementing index of each element in the array.
<?php $arr = array(10, 20, 30, 40, 50); foreach ($arr as $k=>$v) { echo "Key: $k => Val: $v \n"; } ?>
It will produce the following output −
Key: 0 => Val: 10 Key: 1 => Val: 20 Key: 2 => Val: 30 Key: 3 => Val: 40 Key: 4 => Val: 50
Iterating an Associative Array using "foreach" Loop
An associative array is a collection of key-value pairs. To iterate through an associative array, the second variation of foreach syntax is suitable. Each element in the array is unpacked in two variables each taking up the value of key and its value.
Example
Here is an example in which an array of states and their respective capitals is traversed using the foreach loop.
<?php $capitals = array( "Maharashtra"=>"Mumbai", "Telangana"=>"Hyderabad", "UP"=>"Lucknow", "Tamilnadu"=>"Chennai" ); foreach ($capitals as $k=>$v) { echo "Capital of $k is $v \n"; } ?>
It will produce the following output −
Capital of Maharashtra is Mumbai Capital of Telangana is Hyderabad Capital of UP is Lucknow Capital of Tamilnadu is Chennai
However, you can still use the first version of foreach statement, where only the value from each key-value pair in the array is stored in the variable. We then obtain the key corresponding to the value using the array_search() function that we had used before.
<?php $capitals = array( "Maharashtra"=>"Mumbai", "Telangana"=>"Hyderabad", "UP"=>"Lucknow", "Tamilnadu"=>"Chennai" ); foreach ($capitals as $pair) { $cap = array_search($pair, $capitals); echo "Capital of $cap is $capitals[$cap] \n"; } ?>
Iterating a 2D Array using "foreach" Loop
It is possible to declare a multi-dimensional array in PHP, wherein each element in an array is another array itself. Note that both the outer array as well as the sub-arry may be an indexed array or an associative array.
In the example below, we have a two-dimensional array, which can be called as an array or arrays. We need nested loops to traverse the nested array structure as follows −
<?php $twoD = array( array(1,2,3,4), array("one", "two", "three", "four"), array("one"=>1, "two"=>2, "three"=>3) ); foreach ($twoD as $idx=>$arr) { echo "Array no $idx \n"; foreach ($arr as $k=>$v) { echo "$k => $v" . "\n"; } echo "\n"; } ?>
It will produce the following output −
Array no 0 0 => 1 1 => 2 2 => 3 3 => 4 Array no 1 0 => one 1 => two 2 => three 3 => four Array no 2 one => 1 two => 2 three => 3