foreach

suggest change
The foreach statement is used to loop through arrays.

For each iteration the value of the current array element is assigned to $value variable and the array pointer is moved by one and in the next iteration next element will be processed.

The following example displays the items in the array assigned.

$list = ['apple', 'banana', 'cherry'];

foreach ($list as $value) {
    echo "I love to eat {$value}. ";
}

The expected output is:

I love to eat apple. I love to eat banana. I love to eat cherry.

You can also access the key / index of a value using foreach:

foreach ($list as $key => $value) {
    echo $key . ":" . $value . " ";
}

//Outputs - 0:apple 1:banana 2:cherry

By default $value is a copy of the value in $list, so changes made inside the loop will not be reflected in $list afterwards.

foreach ($list as $value) {
    $value = $value . " pie";
}
echo $list[0]; // Outputs "apple"

To modify the array within the foreach loop, use the & operator to assign $value by reference. It’s important to unset the variable afterwards so that reusing $value elsewhere doesn’t overwrite the array.

foreach ($list as &$value) { // Or foreach ($list as $key => &$value) {
    $value = $value . " pie";
}
unset($value);
echo $list[0]; // Outputs "apple pie"

You can also modify the array items within the foreach loop by referencing the array key of the current item.

foreach ($list as $key => $value) {
    $list[$key] = $value . " pie";
}
echo $list[0]; // Outputs "apple pie"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Loops:
* Loops
* break
* foreach
* for
* while

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR