PHPのお勉強!

PHP TOP

foreach

(PHP 4, PHP 5, PHP 7)

foreach は、配列を反復処理するための便利な方法です。 foreach が使えるのは配列とオブジェクトだけであり、 別のデータ型や初期化前の変数に対して使うとエラーになります。 この構造には二種類の構文があります。

foreach (array_expression as $value)
    文
foreach (array_expression as $key => $value)
    文

最初の形式は、array_expressionで指定した配列に 関してループ処理を行います。各反復において現在の要素の値が $valueに代入され、内部配列ポインタが一つ前に 進められます。(よって、次の反復では次の要素を見ることになります。)

2番目の形式は、さらに各反復で現在の要素のキーを変数 $keyに代入します。

オブジェクトの反復処理をカスタマイズ することもできます。

注意:

PHP 5 では、foreachの実行開始時に内部配列ポインタは、 配列の先頭要素を指すように自動的にリセットされます。 このため、foreachループの前に reset()をコールする必要はありません。

PHP 5 では、foreach は内部の配列ポインタに依存するので、 ループ内で配列ポインタを変更すると予期せぬ振る舞いを引き起こします。

PHP 7 では、foreach は内部の配列ポインタを使わなくなりました。

ループの中で配列の要素を直接変更したい場合は、 $value の前に & をつけます。こうすると、変数には リファレンス が代入されることになります。

<?php
$arr 
= array(1234);
foreach (
$arr as &$value) {
    
$value $value 2;
}
// $arr は array(2, 4, 6, 8) となります
unset($value); // 最後の要素への参照を解除します
?>

警告

foreach ループを終えた後でも、 $value は配列の最後の要素を参照したままとなります。 unset() でその参照を解除しておくようにしましょう。 さもないと、次のような目に遭うことになるでしょう。

<?php
$arr 
= array(1234);
foreach (
$arr as &$value) {
    
$value $value 2;
}
// この時点で、$arr は array(2, 4, 6, 8) となります

// unset($value) しなければ、$value は今でも最後の要素 ($arr[3]) を指したままです

foreach ($arr as $key => $value) {
    
// $arr[3] が、$arr の各要素で上書きされて...
    
echo "{$key} => {$value} ";
    
print_r($arr);
}
// ...つまり、二番目から最後までの値が最後の値にコピーされていきます

// 出力
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

PHP 5.5.0 より前のバージョンでは、$value の参照は、ループ処理される配列が参照可能である場合 (すなわち、 変数である) のみ使用可能です。次のコードは、PHP 5.5.0 以降でしか動作しません。

<?php
foreach (array(1234) as &$value) {
    
$value $value 2;
}
?>

注意:

foreach は、'@' によりエラーメッセージ出力を抑 制する機能をサポートしていません。

使用法を示すためにその他の例を示します。

<?php
/* foreach の例 1: 値のみ */

$a = array(12317);

foreach (
$a as $v) {
    echo 
"Current value of \$a: $v.\n";
}

/* foreachの例2: 値 (説明用に、手動でアクセスする際の表記を出力) */

$a = array(12317);

$i 0/* 説明用 */

foreach ($a as $v) {
    echo 
"\$a[$i] => $v.\n";
    
$i++;
}

/* foreachの例3: キーと値 */

$a = array(
    
"one" => 1,
    
"two" => 2,
    
"three" => 3,
    
"seventeen" => 17
);

foreach (
$a as $k => $v) {
    echo 
"\$a[$k] => $v.\n";
}

/* foreach の例4: 多次元配列 */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach (
$a as $v1) {
    foreach (
$v1 as $v2) {
        echo 
"$v2\n";
    }
}

/* foreach の例5: 動的配列 */

foreach (array(12345) as $v) {
    echo 
"$v\n";
}
?>

ネストした配列の list() による展開

(PHP 5 >= 5.5.0, PHP 7)

PHP 5.5 からは、配列の配列の反復処理ができるようになりました。 値として list() を渡すと、 ネストした配列をループ変数に展開できます。

例を示します。

<?php
$array 
= [
    [
12],
    [
34],
];

foreach (
$array as list($a$b)) {
    
// $a にはネストした配列の最初の要素が含まれ、
    // $b には二番目の要素が含まれます。
    
echo "A: $a; B: $b\n";
}
?>

上の例の出力は以下となります。

A: 1; B: 2
A: 3; B: 4

list() で指定する要素数を、ネストした配列の要素数より少なくしてもかまいません。 その場合は、配列の残りの要素は無視されます。

<?php
$array 
= [
    [
12],
    [
34],
];

foreach (
$array as list($a)) {
    
// $b を指定していないことに注目。
    
echo "$a\n";
}
?>

上の例の出力は以下となります。

1
3

list() で指定した変数を埋めるだけの要素が足りないときには、notice が発生します。

<?php
$array 
= [
    [
12],
    [
34],
];

foreach (
$array as list($a$b$c)) {
    echo 
"A: $a; B: $b; C: $c\n";
}
?>

上の例の出力は以下となります。


Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C: 

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C: 

変更履歴

バージョン 説明
7.0.0 foreach が内部の配列ポインタを使わなくなりました。
5.5.0 式から $value を参照できるようになりました。 これより前のバージョンでは、変数からの参照にだけ対応していました。
5.5.0 ネストした配列の list() による展開に対応しました。

add a note add a note

User Contributed Notes 24 notes

up
267
adam dot sindelar at gmail dot com
12 years ago
You can also use the alternative syntax for the foreach cycle:

<?php
foreach($array as $element):
 
#do something
endforeach;
?>

Just thought it worth mentioning.
up
122
php at darkain dot com
7 years ago
"Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()."

I cannot stress this point of the documentation enough! Here is a simple example of exactly why this must be done:

<?php
$arr1
= array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);

foreach (
$arr1 as $key => &$val) {}
foreach (
$arr2 as $key => $val) {}

var_dump($arr1);
var_dump($arr2);
?>

The output is:
array(3) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> &int(6) }
array(3) { ["x"]=> int(4) ["y"]=> int(5) ["z"]=> int(6) }

Notice how the last index in $arr1 is now the value from the last index in $arr2!
up
50
KEINOS
2 years ago
Even though it is not mentioned in this article, you can use "break" control structure to exit from the "foreach" loop.

<?php

$array
= [ 'one', 'two', 'three', 'four', 'five' ];

foreach(
$array as $value ){
    if(
$value == 'three' ){
        echo
"Number three was found!";
        break;
    }
}

?>
up
55
tedivm at tedivm dot com
11 years ago
foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other.

<?php
$arr
= array(1,2,3,4,5,6,7,8,9);

foreach(
$arr as $key=>$value)
{
    unset(
$arr[$key + 1]);
    echo
$value . PHP_EOL;
}
?>
Output:
1 2 3 4 5 6 7 8 9

<?php
$arr
= array(1,2,3,4,5,6,7,8,9);

while (list(
$key, $value) = each($arr))
{
    unset(
$arr[$key + 1]);
    echo
$value . PHP_EOL;
}
?>
Output:
1 3 5 7 9


[EDIT BY danbrown AT php DOT net: Contains a typofix by (scissor AT phplabs DOT pl) on 30-JAN-2009.]
up
26
John
3 years ago
WARNING: Looping through "values by reference" for "extra performance" is an old myth. It's actually WORSE!

<?php

function one($arr) {
    foreach(
$arr as $val) { // Normal Variable
       
echo $val;
    }
}

function
two($arr) {
    foreach(
$arr as &$val) { // Reference To Value
       
echo $val;
    }
}

$a = array( 'a', 'b', 'c' );
one($a);
two($a);

?>

Which do you think is faster?

Lots of people think the answer is two() because it uses "reference to value, which it doesn't have to copy each value when it loops".

Well, that's totally wrong!

Here's what actually happens:

* one():

- This function takes an array as argument ($arr).
- The array function argument itself isn't passed by reference, so the function knows it isn't allowed to modify the original at all.
- Then the foreach loop happens. The array itself wasn't passed by reference to the function, so PHP knows that it isn't allowed to modify the outside array, so it therefore makes a copy of the array's internal iteration offset state (that's just a simple number which says which item you are currently at during things like foreach()), which costs almost no performance or memory at all since it's just a small number.
- Next, it uses that copied iteration offset to loop through all key/value pairs of the array (ie 0th key, 1st key, 2nd key, etc...). And the value at the current offset (a PHP "zval") is assigned to a variable called $val.
- Does $val make a COPY of the value? That's what MANY people think. But the answer is NO. It DOESN'T. It re-uses the existing value in memory. With zero performance cost. It's called "copy-on-write" and means that PHP doesn't make any copies unless you try to MODIFY the value.
- If you try to MODIFY $val, THEN it will allocate a NEW zval in memory and store $val there instead (but it still won't modify the original array, so you can rest assured).

Alright, so what's the second version doing? The beloved "iterate values by reference"?

* two():

- This function takes an array as argument ($arr).
- The array function argument itself isn't passed by reference, so the function knows it isn't allowed to modify the original at all.
- Then the foreach loop happens. The array itself wasn't passed by reference to the function, so PHP knows that it isn't allowed to modify the outside array.
- But it also sees that you want to look at all VALUES by reference (&$val), so PHP says "Uh oh, this is dangerous. If we just give them references to the original array's values, and they assign some new value to their reference, they would destroy the original array which they aren't allowed to touch!".
- So PHP makes a FULL COPY of the ENTIRE array and ALL VALUES before it starts iterating. YIKES!

Therefore: STOP using the old, mythological "&$val" iteration method! It's almost always BAD! With worse performance, and risks of bugs and quirks as is demonstrated in the manual.

You can always manually write array assignments explicitly, without references, like this:

<?php

$a
= array(1, 2, 3);
foreach(
$a as $key => $val) {
  
$a[$key] = $val * 10;
}
// $a is now [10, 20, 30]

?>

The main lesson is this: DON'T blindly iterate through values by reference! Telling PHP that you want direct references will force PHP to need to copy the WHOLE array to protect its original values! So instead, just loop normally and trust the fact that PHP *is* actually smart enough to never copy your original array's values! PHP uses "copy-on-write", which means that attempting to assign something new to $val is the ONLY thing that causes a copying, and only of that SINGLE element! :-) But you never do that anyway, when iterating without reference. If you ever want to modify something, you use the "$a[$key] = 123;" method of updating the value.

Enjoy and good luck with your code! :-)
up
14
mustaroad
3 years ago
in foreach if you want to iterate through a specific column in a nested arrays for example:

$arr = array(
     [1, 2, 3,   4],
     [14, 6, 7,  6],
     [10, 2 ,3 , 2],
);

when we want to iterate on the third column we can use:

foreach( $arr as list( , , $a)) {
    echo "$a\n";
}

this will print:
3
7
3
up
22
Fred
5 years ago
If you want to use the list for multidimension arrays, you can nest several lists:

<?php
$array
= [
    [
1, 2, array(3, 4)],
    [
3, 4, array(5, 6)],
];

foreach (
$array as list($a, $b, list($c, $d))) {
    echo
"A: $a; B: $b; C: $c; D: $d;<br>";
};
?>

Will output:
A: 1; B: 2; C: 3; D: 4;
A: 3; B: 4; C: 5; D: 6;

And:

<?php
$array
= [
    [
1, 2, array(3, array(4, 5))],
    [
3, 4, array(5, array(6, 7))],
];

foreach (
$array as list($a, $b, list($c, list($d, $e)))) {
    echo
"A: $a; B: $b; C: $c; D: $d; E: $e;<br>";
};
Will output:
A: 1; B: 2; C: 3; D: 4; E: 5;
A: 3; B: 4; C: 5; D: 6; E: 7;
?>
up
21
Alastair Hole
6 years ago
What happened to this note:
"Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it."

Is this no longer the case?
It seems only to remain in the Serbian documentation: http://php.net/manual/sr/control-structures.foreach.php
up
17
Oleg englishman at bigmir dot net
10 years ago
For those who'd like to traverse an array including just added elements (within this very foreach), here's a workaround:

<?php
$values
= array(1 => 'a', 2 => 'b', 3 => 'c');
while (list(
$key, $value) = each($values)) {
    echo
"$key => $value \r\n";
    if (
$key == 3) {
       
$values[4] = 'd';
    }
    if (
$key == 4) {
       
$values[5] = 'e';
    }
}
?>

the code above will output:

1 => a
2 => b
3 => c
4 => d
5 => e
up
-1
me
2 months ago
It is not documented, but when modifying the array within foreach:
PHP seems to create a snapshot, or a copy of the entire array ("copy on write"?) when it starts the foreach loop, so changes on the iterated array in the loop have no effect on the started loop.

$a = [1,2,3];

foreach ($a as $key => $value) {
    if($value == 1) {
        $a[3] = 1;
        $a[1] = 999999;
        unset($a[0]);
        echo "Inner loop start: \n";
        foreach ($a as $key2 => $value2) {
            echo "$key2 => $value2";
            echo "\n";
        }
        echo "Inner loop end \n";
    }
    echo "$key => $value";
    echo "\n";
}

echo "Next iteration: \n";

foreach ($a as $key => $value) {
    echo "$key => $value";
    echo "\n";
}

Result:

Inner loop start:
1 => 999999
2 => 3
3 => 1
Inner loop end
0 => 1
1 => 2
2 => 3
Next iteration:
1 => 999999
2 => 3
3 => 1
up
3
Delian Krustev
7 years ago
I want to add some inline comments to dtowell's piece of code about the iteration by reference:

<?php

$a
= array('abe','ben','cam');

foreach (
$a as $k=>&$n)
   
$n = strtoupper($n);

# At the end of this cycle the variable $n refers to the same memory as $a[2]
# So when the second "foreach" assigns a value to $n :

foreach ($a as $k=>$n) // notice NO reference here!
   
echo "$n\n";

# it is also modifying $a[2] .
# So on the three repetitions of the second "foreach" the array will look like:
# 1. ('abe','ben','abe') - assigned the value of the first element to the last element
# 2. ('abe','ben','ben') - assigned the value of the second element to the last element
# 3. ('abe','ben','ben') - assigned the value of the third element to itself

print_r($a);
?>
up
-4
peter georgiev
3 years ago
I want just to mention that John is not entirely true.

Simple field test:

$m = microtime(1); $array = range(1,1000000); foreach ($array as &$i) { $i = 4; } echo microtime(1) - $m;

Result: 0.21731400489807

$m = microtime(1); $array = range(1,1000000); foreach ($array as $k => $i) { $array[$k] = 4; } echo microtime(1) - $m;

Result: 0.51596283912659

PHP Version: PHP 5.6.30 (cli) (built: Jan 18 2017 19:47:36)

Conclusion: Working with reference, although a bit dangerous is >2 times faster. You just need to know well what are you doing.

Best of luck and happy coding all
up
-10
sebastian dot goendoer at NOSPAM dot telekom dot de
4 years ago
String keys of associative arrays, for which is_numeric() is true and which can be type-juggled to an int will be cast to an int! If the key is on the other hand a string that can be type-juggled into a float, it will stay a string. (Observed on PHP 7.0.0RC8)

<?php
$arr
= array();
$arr[0] = "zero";            // will stay an int
$arr["1"] = "one";            // will be cast to an int !
$arr["two"] = "2";            // will stay a string
$arr["3.5"] = "threeandahalf";    // will stay a string

foreach($arr as $key => $value) {
   
var_dump($key);
}
?>

The output will be

int(0)
int(1)
string(3) "two"
string(3) "3.5"
up
-10
Anonymous
5 years ago
modifying array while foreach'ing it(yeah, such slime code;-)
if elements were added on last iteration or into array with 1 element, then added elements wont be iterated as foreach checks for pointer before iteration cycle
so it just quit and added elements wont be treated
up
-15
nehuen
6 years ago
foreach by reference internally deleted and created a new reference in each iteration, so it is not possible to directly use this value as a variable parameter values​​, look at the following example where the problem is observed and a possible solution:

<?php
class test
{
    private
$a = false;
    private
$r = null;
    public function
show(&$v)
    {
        if(!
$this->a)
        {
           
$this->a = true;
           
$this->r = &$v;
        }
       
var_dump($this->r);
    }
    public function
reset()
    {
       
$this->a = false;   
    }
}

$t = new test();

$a = array(array(1,2),array(3,4),array(5,6));
foreach(
$a as &$p)
   
$t->show($p);
   
/* Output obtain:
    array (size=2)
      0 => int 1
      1 => int 2
    array (size=2)
      0 => int 1
      1 => int 2
    array (size=2)
      0 => int 1
      1 => int 2
*/
 
 
$t->reset();
  foreach(
$a as $p)
  {
   
$b = &$p;
   
$t->show($b);
  }
 
/* Output obtain:
    array (size=2)
      0 => int 1
      1 => int 2
    array (size=2)
      0 => int 3
      1 => int 4
    array (size=2)
      0 => int 5
      1 => int 6
*/
up
-26
nobody at nobody dot com
8 years ago
<?php
$d3
= array('a'=>array('b'=>'c'));
foreach(
$d3['a'] as &$v4){}
foreach(
$d3 as $v4){}
var_dump($d3);
?>
will get something look like this:
array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    &array(1) {
      ["b"]=>
      *RECURSION*
    }
  }
}
then you try to walk some data with this array.
the script run out of memory and connect reset by peer

the document says:
Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

so what I learn is that NEVER ignore """Warning""" in document....
up
-10
ahmad dot mayahi at gmail dot com
3 years ago
foreach retains the state of internal defined variable:

<?php
/**
Result for this array is:
Hello World
Hello World
Hello World
*/
$arr = ["a", "b", "c"];
$title = "";
foreach (
$arr as $r) {
    if (
$r == "a") {
        
$title = "Hello World";  
    }
    echo
$title."<br>";
}
?>

in this case, all we need to do is to add an else statement:
<?php
$arr
= ["a", "b", "c"];
$title = "";
/**
This prints:
Hello World
*/
foreach ($arr as $r) {
    if (
$r == "a") {
        
$title = "Hello World";  
    } else {
       
$title = "";
    }
    echo
$title."<br>";
}
?>
up
-19
pnc at balintx dot me
4 years ago
Just a simple strange behavior I have ran into:

If you accidentally put a semicolon after the foreach statement, you get no errors, but the loop will only run on the last element of the array:
<?php
$array
= array(1,2,3);
foreach (
$array as $key);
{
    echo
$key;
}
// output: 3
?>

Correctly:
<?php
$array
= array(1,2,3);
foreach (
$array as $key)
{
    echo
$key;
}
// output: 123
?>

It took me a while to find that semicolon.
up
-5
dan
7 months ago
Having to unset the reference manually completely destroys the practicality of using a referenced variable.

If you make the small mistake of forgetting/deleting the unset line your code might silently mix data, the risk is too high for little gain.

If you need to reassign the value, it is way better to just use:
<?php
$array
[$key] = $newvalue;
?>
up
-40
Ashus
7 years ago
If you wondered how to create a list of all possible combinations of variable amount of arrays (multiple foreach), you might use this:

<?php

$a
[0] = array('a1','a2');
$a[1] = array('b1','b2','b3');
$a[2] = array('c1','c2');

function
getAllCombinations($a,$i,$s)
    {
    foreach (
$a[$i] as $v)
        {
        if (!isset(
$a[$i+1]))
            {
            echo
$s.$v."\n";
            } else {
           
getAllCombinations($a,$i+1,$s.$v);
            }
        }
    return
$s;
    }

echo
getAllCombinations($a,0,'');

?>

the result:

a1b1c1
a1b1c2
a1b2c1
a1b2c2
a1b3c1
a1b3c2
a2b1c1
a2b1c2
a2b2c1
a2b2c2
a2b3c1
a2b3c2
up
-9