Help to see how it returns null
This post was last edited by Snowlove on 2013-06-17 18:27:34
function Newtripos ($str, $findstr, $count, $off =0) {
$pos =stripos ($str, $findstr, $off);
$count--;
if ($count >0 && $pos!=false) {
$pos =newtripos ($str, $findstr, $count, $pos + 1);
}else{
Var_dump ($pos);
return $pos;
}
}
$a = "456123456455654466";
$b =newtripos ($a, ' 6 ', 4);
Var_dump ($b);
?>
Display $b after execution is null. And before the function returns, the Var_dump ($pos) is executed, and the display is int (16).
Why would var_dump ($b) be null?
Share to:
------Solution--------------------
You used recursion, return $pos; It will be used for $pos =newtripos ($str, $findstr, $count, $pos + 1) after entering recursion;
And you're not dealing with $pos in this branch (that is, returning the results to the upper-level recursion)
I may not be able to understand, see the code:
function Newtripos ($str, $findstr, $count, $off =0) {
$pos =stripos ($str, $findstr, $off);
$count--;
if ($count >0 && $pos!=false) {
$pos =newtripos ($str, $findstr, $count, $pos + 1);
}
return $pos;
}
------Solution--------------------
The difference is mostly because when else is not removed, the equivalent
if ($count >0 && $pos!=false) {
$pos =newtripos ($str, $findstr, $count, $pos + 1);
return null;
}else{
Var_dump ($pos);
return $pos;
}
}
?>
And when you remove else, it is
if ($count >0 && $pos!=false) {
$pos =newtripos ($str, $findstr, $count, $pos + 1);
return $pos;
}else{
Var_dump ($pos);
return $pos;
}
}
?>