开发者

How to make sure the value is reset in a 'foreach' loop in PHP?

I was writing a simple PHP page and a few foreach loop开发者_高级运维s were used.

Here are the scripts:

$arrs = array("a", "b", "c");

foreach ($arrs as $arr) {
    if(substr($arr,0,1)=="b") {
        echo "This is b";
    }     
} // End of first 'foreach' loop, and I didn't use 'ifelse' here.

And when this foreach ends, I wrote another foreach loop in which all the values in the foreach loop was the same as in the previous foreach.

foreach ($arrs as $arr) {
    if(substr($arr,0,1)=="c") {
        echo "This is c";
    }     
}

I am not sure if it is a good practice to have two foreach loops with the same values and keys.

Will the values get overwritten in the first foreach loop?


It's OK until you start using references and then you can get strange behaviour, for example:

<?php
$array = array(1,2,3,4);
//notice reference &
foreach ($array as & $item) {   }

$array2 = array(10, 11, 12, 13);
foreach ($array2 as $item) {   }

print_r($array);

Outputs this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 13
)

Because the first foreach leaves $item as a reference to $array[3], $array[3] is sequentially set to each value in $array2.

You can solve this be doing unset($item) after the first foreach, which will remove the reference, but this isn't actually an issue in your case, as you are not using references with foreach.


Two notable notes from the documentation of foreach:

Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

and

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.


Because you're not writing to the array, only reading from it and printing stuff out, no values in the array will be changed.

You can save time looping through the array twice though by doing this:

$arrs = array("a", "b", "c");

foreach ($arrs as $arr) {
    if(substr($arr,0,1)=="b") {
        echo "This is b";
    }
    if(substr($arr,0,1)=="c") {
        echo "This is c";
    }
}


All you need is 1 foreach loop.

Or an even shorter approach to what Jon said, is this:

$arrs = array("a", "b", "c");

foreach ($arrs as $arr)
    if ($arr != "a")
        echo 'This is ' . $arr;

This is much easier and faster than using substr, since you are already using a foreach loop. And try not to pollute it with a ton of if statements, if you find yourself doing this, it's better to use a switch statement, much faster.

Cheers :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜