How to make sure the value is reset in a 'foreach' loop in PHP? -
i writing simple php page , few foreach loops used.
here scripts:
$arrs = array("a", "b", "c"); foreach ($arrs $arr) { if(substr($arr,0,1)=="b") { echo "this b"; } } // end of first 'foreach' loop, , didn't use 'ifelse' here. and when foreach ends, wrote foreach loop in values in foreach loop same in previous foreach.
foreach ($arrs $arr) { if(substr($arr,0,1)=="c") { echo "this c"; } } i not sure if practice have 2 foreach loops same values , keys.
will values overwritten in first foreach loop?
it's ok until start using references , can strange behaviour, example:
<?php $array = array(1,2,3,4); //notice reference & foreach ($array & $item) { } $array2 = array(10, 11, 12, 13); foreach ($array2 $item) { } print_r($array); outputs this:
array ( [0] => 1 [1] => 2 [2] => 3 [3] => 13 ) because first foreach leaves $item reference $array[3], $array[3] sequentially set each value in $array2.
you can solve doing unset($item) after first foreach, remove reference, this isn't issue in case, not using references foreach.
Comments
Post a Comment