Huy Hoa
  • Home
  • Code Learn
    • WordPress
    • Woocommerce
    • Joomla
    • PHP
    • SEO – Marketing
  • Vietnam
  • Healthcare
    • Womens Health
  • Beauty
  • Lifehack
  • Free Tools
    • BMI Calculator
    • Upside Down Text
    • Vietnamese Typing
  • Contact Us
Nổi bật
  • How do you treat an infected belly button piercing?
  • Seizures in Dogs: Causes, Symptoms, Types, and Treatments
  • Vietnamese symbols throughout 4000 years history
  • 4 Day Push-Pull Workout Routine for Mass and Strength
  • The Best Push Pull Legs Routine For Building Muscle and Strength
Tuesday, August 5
Huy Hoa
  • Home
  • Code Learn
    • WordPress
    • Woocommerce
    • Joomla
    • PHP
    • SEO – Marketing
  • Vietnam
  • Healthcare
    • Womens Health
  • Beauty
  • Lifehack
  • Free Tools
    • BMI Calculator
    • Upside Down Text
    • Vietnamese Typing
  • Contact Us
Huy Hoa
Home»Code Learn»PHP foreach: Tutorials and Examples

PHP foreach: Tutorials and Examples

Facebook Twitter Pinterest LinkedIn Tumblr Email
PHP Foreach
PHP Foreach

The PHP foreach statement executes the command in an array or an object. Foreach loop in the array or object it will execute the statement once, doing so from the first loop to the last loop. Unless another command prevents or navigates PHP foreach.

foreach() loop appears in most popular CMS using PHP such as WordPress, Joomla, Laravel, Mambo,…

The PHP foreach statement executes only one statement for each element in the array.

Table of Contents

Syntax of PHP foreach():

Foreach Loop in PHP

There are two syntaxes of the PHP foreach statement:

1
2
3
4
foreach (iterable_expression as $value)
{
    statement
}

Or

1
2
3
foreach (iterable_expression as $key=>$value) {
  statement(s)
}

Code & Explanation:

As we learned in the Syntax of PHP foreach() section above, the foreach function can work on both indexed and associative arrays.
We will learn in turn how the PHP foreach function works on both these types of arrays.
We will first look at how the foreach() function works on an indexed array.

PHP Foreach() on Indexed arrays:

Suppose we have an indexed array of fruits as follows $array_fruits. Then we will run the PHP foreach function to display each fruit, one per line.

1
2
3
4
5
6
<?php
$array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry");
foreach ($array_fruits as $value) {
  echo "$value <br>";
}
?>

The above syntax can be read as “for each element in array $array_fruits accessed as $value, execute echo and newline statement”. And here is the result

1
2
3
4
5
6
7
Apple
Apricot
Avocado
Banana
Berry
Cantaloupe
Cherry

At each iteration of the foreach loop, you can access the corresponding element of the array for that iteration, via the $value variable. You can change the variable name $value to whatever variable name you want. The example above if you don’t like $value, you can set it to $fruit for example.

Then the code will look like this:

1
2
3
4
5
6
<?php
$array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry");
foreach ($array_fruits as $fruit) {
  echo "$fruit <br>";
}
?>

PHP Foreach() on an associative array:

Next we will learn how PHP Foreach() Loop works on an associative array:

1
2
3
4
5
6
7
<?php
$football_teams = array("name" => "Ronaldo", "email" => "[email protected]", "age" => 36, "gender" => "male");
// Loop through employee array
foreach($football_teams as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>

As such, in an associative array, you will access the key and value in each iteration using the $key and $value variables. Similar to an indexed array, in an associative array you can also change the $key and $value variables to whatever you want.

As we have seen, associative arrays differ from indexed arrays in the sense that associative arrays use descriptive names for id keys. As the example above we have 4 keys corresponding to 4 values for the $football_teams array

The example above will produce the following result

1
2
3
4
name: Ronaldo
email: ronaldo@gmail.com
age: 36
gender: male

Php Nested Foreach On Multi Dimensional Array

For PHP Multidimensional Arrays you can use nested foreach. The level of nested foreach statements is equal to the size of the multidimensional array.

Below is a two dimensional array and uses nested foreach to iterate through the elements of the array and display the results.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$football_teams =array(
"0" => array("name" => "Messy", "email" => "[email protected]", "age" => 34, "gender" => "male"),
"1" => array("name" => "Ronaldo", "email" => "[email protected]", "age" => 36, "gender" => "male")
);  
foreach($football_teams as $key => $team_info) {
   $information = '';
   foreach($team_info as $keyname => $team) {
    $information .= $keyname.": ".$team.", ";
  }
  echo "$key: $information<br />";
}
?>

The results will show up like this:

1
2
0: name: Messy, email: messy@gmail.com, age: 34, gender: male,
1: name: Ronaldo, email: ronaldo@gmail.com, age: 36, gender: male,

Another example of Loop through an PHP array using Nesting foreach() loops

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$array2 = array(
    array(date('Y', strtotime("-12 months ".date('Y-m-d')."")), date('Y'), date('Y', strtotime("+12 months ".date('Y-m-d').""))),
    array(4, 5, 6),
    array(1, 2, 3)
);
/*
date('Y', strtotime("-12 months ".date('Y-m-d')."")) // Will show the previous year - like 2020
date('Y') // Will show the current year - like 2021
date('Y', strtotime("+12 months ".date('Y-m-d')."")) // Will show the next year - 2022
*/
foreach ($array2 as $array1) {
    foreach ($array1 as $value) {
        echo $value;
        echo " ";
    }
    echo "<br>";
}
?>

The result will show like this

1
2
3
2020, 2021, 2022,
4, 5, 6,
1, 2, 3,

Find the foreach index

To find the foreach index, we just need to show the $key. $key is the index of each $array element

For example:

Going back to the example with the array of fruits above. We will show get the index of the current iteration of a foreach loop and the corresponding value on each line.

1
2
3
4
5
6
7
8
<?php
echo "Using foreach with index <br />";
$array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry");
foreach($array_fruits as $key=>$value)
{
echo "$key => $value.\n [=========>] Here \$key = $key, \$value = $value<br />";
}
?>

Result:

1
2
3
4
5
6
7
8
Using foreach with index
0 => Apple. [=========] Here $key = 0, $value = Apple
1 => Apricot. [=========] Here $key = 1, $value = Apricot
2 => Avocado. [=========] Here $key = 2, $value = Avocado
3 => Banana. [=========] Here $key = 3, $value = Banana
4 => Berry. [=========] Here $key = 4, $value = Berry
5 => Cantaloupe. [=========] Here $key = 5, $value = Cantaloupe
6 => Cherry. [=========] Here $key = 6, $value = Cherry

Count number of iterations in a foreach loop

If you want to count the total number of elements in the array in the foreach, you can use the index above, or use the count() function to display the total.

1
$total = count($array_fruits);

Another way is to display all the values of each element with its position with $i and $i++

1
2
3
4
5
6
7
<?php
$i = 0;
foreach ($array_fruits as $fruit) {
    $fruit[5];// Replace number with the number you want to display. For example if there are 7 $fruit in this foreach, I want get the value : 5, then it will be $fruit[5]
    $i++;
}
?>

Remove an array element in a foreach loop

Use unset() function to remove array elements in foreach loop. The unset() function is a built-in PHP function that is used to unset a specified variable.

First, we still use PHPforeach(), then check the loop, if we encounter a value we need to delete, we will use the unset() function to remove it. The loop continues to run after that without any effect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
// Declare an array and initialize it
$array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry");
// Display the array elements
echo "<pre> "; print_r($array_fruits);  echo "  </pre>";
// Use foreach loop to remove array element
foreach($array_fruits as $k => $fruit)
{
    if($fruit == "Apple")
    {
        unset($array_fruits[$k]);
    }
}
// Display the array elements
echo "This is array after remove Apple from \$array_fruits <pre> ";
print_r($array_fruits);  echo "  </pre>";
?>

The output of the example above will look like this:

remove an array element in a PHP foreach loop

Break a foreach loop in PHP

When using loops you may also end the loop or skip the current iteration

1
2
3
4
5
6
7
8
9
10
11
<?php
$array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry");
foreach($array_fruits as $key=> &$value)
{
echo "$key => $value.\n [=========] Here \$key = $key, \$value = $value<br />";
if($key == 3) // Only runs to the 4th loop ($key = 3 because $key starts at 0). You can compare $key < 3, it will only run 3 loops of 0.1, 2. The same goes for other comparisons of the if . function
{
break;
}
}
?>

Break will completely stop the execution of foreach at the time it reaches the specified requirement. This means that all subsequent iterations will no longer be able to execute the foreach statement.

Modify an array within a PHP foreach loop

If you are using foreach to iterate over an array and you want to modify the array itself, there are two ways to do it.

The first is to point to the array element you want to edit using the $array[$key] syntax (so you have to use the foreach on an associative array $key => $value syntax in the foreach).

Another way is to define $value as a reference and edit it directly. Take a look at the two examples below:

Example 1:

1
2
3
4
5
6
$array = array(1000, 2000);
foreach ($array as $key => $value)
{
   $array[$key] += 100;
}
print_r($array);

Example 2:

1
2
3
4
5
6
$array = array(1000, 2000);
foreach ($array as $key => &$value)
{
   $value += 100;
}
print_r($array);

In both examples above, the result will be returned like this:

1
2
3
4
5
Array
(
  [0] => 1100
  [1] => 2100
)

Performance of $key => $value

PHP Foreach loops support both $array as $value and $array as $key => $value  syntax. The first syntax has the fastest performance.

In my testing, using the second syntax resulted in 50% longer execution times. If you don’t need the key, you should probably use the first syntax.

Even so, the numbers are so small that you won’t notice any difference in real-life situations.

So don’t worry too much about performance (on my test machine, the two tests ran between 0.2 and 0.3 seconds, in an array of 10 million elements).

Summary

The $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,…

In PHP, associative arrays look like this:
Use foreach ($array as $element) to iterate over the elements of an indexed array.
Use foreach ($array as $key => $value) to iterate over the elements of an associative array.

Some possible errors when using foreach loop in php

The most common error is an error related to non-standard arrays or objects, so foreach loop cannot run.
When you feed a PHP  foreach loop with data that are not an array, you get a warning:

Warning: Invalid argument supplied for foreach() in

The workaround is extremely simple, that before launching the PHP foreach loop, we will check if the object is an array or an object?

1
2
3
4
5
6
7
if (is_array($array) || is_object($array))
{
    foreach ($array as $value)
    {
       // Do statement here
    }
}

 

PHP
Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Previous Article11 Best Methods to Remove Hair Dye from Skin
Next Article How to read allergy skin test results?
Huy Hoa
  • Website

Related Posts

30+ Useful Custom WooCommerce Functions for Your WordPress Site

Optimize performance and security for WordPress using .htaccess

How to get post data in WordPress?

woocommerce_form_field() user guide and 10 sample examples

5 examples of getting Post by ID & 11 Ways to Get Post ID in WordPress

These 70+ Specialized Blogs About WordPress Will Help Bloggers Succeed

wp_get_attachment_image_src() – a WordPress Function to Returns Array of Image Data

How to Fix PhpMyAdmin Error Incorrect Format Parameter

Leave A Reply Cancel Reply

Wordpress Themes & Plugins

These 70+ Specialized Blogs About WordPress Will Help Bloggers Succeed

Want to learn from top WordPress blog developers? If you are managing and developing a website with WordPress, you always want to stay up to…

woocommerce_form_field() user guide and 10 sample examples

PHP foreach: Tutorials and Examples

How to get post data in WordPress?

How to Fix PhpMyAdmin Error Incorrect Format Parameter

5 examples of getting Post by ID & 11 Ways to Get Post ID in WordPress

The 41+ best free and premium WooCommerce themes

Trending

Hang Ma Street – The Colour Culture of Old Quarter of Hanoi

Hang Ma Street is one of the bustling commercial street typical of past and present Hanoi. Hang Ma Street runs from the intersection Hang Duong…

Divorce puts your heart at risk

Awesome Destinations for Traditional Textiles in Vietnam

Ngo Mon Gate – The beautiful of Hue citadel

Flower villages in Hanoi are busy preparing for Tet flower season

5 Famous Landmarks in Vietnam Dong (Vietnamese Currency)

Is Maui good for your hair? Checkout this detailed review before buying

Largest supermarket chain & 10 biggest supermarkets in Vietnam

Hang Luoc Street – Colour culture street in Vietnamese New Year

West Lake – Famous Landscape in Hanoi

Heavy Snorers, Sleep Apnea Patients at Increased Risk to have Memory and Thinking Problems

Healthy Eating Habits: Anyone up for Yoga?

Is It Better to Do Full-body Workouts or Split Focused Routines?

What cannot be used to dry utensils?

Vietnamese Souvenirs: 21 best things to buy for gifts in Vietnam

Latest Post

How do you treat an infected belly button piercing?

Seizures in Dogs: Causes, Symptoms, Types, and Treatments

Vietnamese symbols throughout 4000 years history

4 Day Push-Pull Workout Routine for Mass and Strength

The Best Push Pull Legs Routine For Building Muscle and Strength

The 41+ best free and premium WooCommerce themes

Is it normal if you have a headache or temple pain after tooth extraction?

Can Dogs Eat Strawberries? Safety guide to avoid poisonous to dogs

Pain meds for dogs: what can I give my dog for pain relief?

Can dogs get headaches and how do you know?

© 2025 All Rights Reserved HuyHoa.Net. DMCA.com Protection Status .
Hosted by Dreamhost. Follow us on Follow Huy Hoa on Google News Google News.
  • About Us
  • Privacy Policy
  • Cookie Policy
  • Contact Us

Type above and press Enter to search. Press Esc to cancel.