Help to see how it returns null

Source: Internet
Author: User
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;
}
}
?>

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.