Help to see how it returns null

Source: Internet
Author: User
This post was last edited by Snowlove on 2013-06-17 18:27:34

 
  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?


Reply to discussion (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;}

Your code is no problem.
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);//The execution of the program here can correctly $pos the value. Continue execution should end function, return $pos
return $pos; This should return the value of the $pos.
}
}
$a = "456123456455654466";
$b =newtripos ($a, ' 6 ', 4); But here $b how not to receive $pos, is a null
Var_dump ($b);
?>

What's the difference between removing the else body and not removing it?

The difference is mostly because when else is not removed, the equivalent

 
  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

 
  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.