How to use a good PHP recursive function return value and return statement? Detailed examples

Source: Internet
Author: User
For a workaround to the PHP recursive function return value problem, and some important points to note when using the return statement in a PHP recursive function, correctly handle the return value of the PHP recursive function to make the code more robust.

The return value problem of PHP recursive function

Example:

Copy Codecode example:

In the above code, else there is a problem. The test executed here does not return a value. So while the condition $i<3 is satisfied return$i the entire function still does not return a value.

Make the following changes to the PHP recursive function above:

Copy Codecode example:

Considerations for return values in PHP recursive functions

When you use return in a PHP recursive function, you will not be able to correctly return the desired situation, and if you do not understand the reason, it is difficult to find the wrong one.

Example:

Copy Codecode example: function Test ($i) {$i-=4; if ($i <3) {return $i;} else{test ($i);}} Echotest (30);

In fact, the else inside of this function is problematic. The result of the polygon execution in this code is that there is no return value. So although the condition $i <3, return $i the entire function will not return a value. Therefore, the above PHP recursive function can be modified as follows:

Copy Codecode example: function Test ($i) {$i-=4; if ($i <3) {return $i;} else{return test ($i);//increment return, let function return value}} echotest (30);
  • Related Article

    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.