The following code works but I would like to know if it is a good practice to have same loop variable in both outer and inner loops? Can this have some major impacts? Is the following code error prone?
function funtion_name($var1, $var2) {
foreach (some_array as $var3 ) {
if ($var3 == $var2) {
// do something.
// Start the inner loop!
foreach (some_array as $var3 ) {
if ($var3 == $var2) {
return false;
}
}
}
}
return true;
}
First of all the using the same variable in loop is not good practice, even if that is re-assigned in each time. In PHP variable memory location reintiated everytime so no harm in it to use the same named variable. In your code 2nd loop will only work when the first if
condition satisfied, so it depends on passing parameters of the function.
<?php
function fun($var1,$var2)
{
$arr1=array(1,2,3,4);
$arr2=array(10,11,12,13);
foreach($arr1 as $var3)
{
if ($var3 == $var2) {
echo $var3;
foreach ($arr2 as $var3 ) {
echo 'inner';
echo $var3;
if ($var3 == $var2) {
}
}
}
}
}
fun(10,1); // here 2nd loop will work as $var2 will satisfy the first condition.
Output : 1inner10inner11inner12inner13
fun(10,11); // here 2nd loop will no work as $var2 will not satisfy the first condition.
Output : '' //no output
Hope I am able to explain you the situation properly.