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 callreset()
before aforeach
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 theforeach
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 :)
精彩评论