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 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:
Outputs this:
Because the first foreach leaves
$itemas 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 firstforeach, which will remove the reference, but this isn’t actually an issue in your case, as you are not using references with foreach.