tags:

views:

92

answers:

4

Hi all,

I was writing a simple PHP page and a few foreach loops 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 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 same values and keys.

Will the values get overwritten in the first foreach loop?

A: 

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";
    }
}
Jon
+2  A: 

It's OK until you start using references and then you can get strange behaviour which can lead to really obscure bugs, 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[4], $array[4] 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.

Tom Haigh
A: 

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.

Felix Kling
A: 

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 :)

SoLoGHoST