• We just launched and are currently in beta. Join us as we build and grow the community.

PHP Foreach Loop

Noname1231

Recurring Income Master
N Rep
0
0
0
Rep
0
N Vouches
0
0
0
Vouches
0
Posts
80
Likes
150
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
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.

foreach (array_expression as $value)
statement

foreach (array_expression as $key => $value)
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

    .

    '<br/>'

    ;
  4. }

Output:

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

An example second given syntax:
The code below is an associative array that stores the student name and their age as the keys with values. And using the foreach loop it prints out the name and age of each student.

  1. $student

    =

    array

    (

    "Allan"

    =>

    "21"

    ,

    "Peter"

    =>

    "25"

    ,

    "Casandra"

    =>

    "27"

    )

    ;
  2. foreach

    (

    $stud

    as

    $key

    =>

    $value

    )

    {
  3. echo

    "Name: $key

    , Age: $value

    <br />"

    ;
  4. }

Output:

Name: Allan, Age: 21
Name: Peter, Age: 25
Name: Casandra, Age: 27

Book traversal links for PHP Foreach Loop

  • ‹ PHP File Handling: Writing to Files
  • Up
  • PHP Forms ›

 

452,292

323,341

323,350

Top