PHP Foreach Loop

0
492

Using PHP programming, one of the most commonly used loop to iterate over an array is a foreach loop. The foreach loop works on arrays and objects, and it will give you an error when you try to use it on a variable with a different data type or an undefined variable.

Here’s the two sample syntax:
The syntax in plain English this statement will do the following, For each item in the specified array execute the statement.

  1. foreach (array_expression as $value)
  2. statement
  3.  
  4. foreach (array_expression as $key => $value)
  5. statement

An example using the first given syntax:
This code below declares an array of months, then it displays each month using foreach loop.

  1. $months = array('JAN', 'FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC');
  2. foreach($months as $Month){
  3. echo $Month.'
  4. ';
  5. }

Output:

JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC

And example using the second syntax:
The code below is an associative array that stores the Employee name and their Work as the keys with values. And using the foreach loop it prints out the name and work of each employee.

  1. $student = array("Adrew"=>"Manager", "Pedro"=>"Clerk", "Juan"=>"HR");
  2. foreach( $stud as $key => $value){
  3. echo "Name: $key, Work: $value
  4. ";
  5. }

Output:

Name: Adrew, Work:Manager
Name:Pedro, Work:Clerk
Name:Juan, Work:HR

 

 

Readers might read also:

 

 

Facebook Comments
(Visited 52 times, 1 visits today)
SHARE
Previous article08 – PHP Basic File System
Next article16 – PHP Type Casting
Hello Itsourcecoders, welcome to itsourcecode.com. I'm Joken Villanueva, MIT a passionate Blogger, Programmer and a Hobbyist. I started Itsourcecode because I wanted to give back and Share all the learnings and knowledge I've learned in my career and I believe through this website I would be able to help and assist those newbie programmers in enhancing their skills from different programming languages. So let us all help each other by sharing our ideas!

LEAVE A REPLY

Please enter your comment!
Please enter your name here