PHP recursive function return occurs when the desired value is not returned correctly

Source: Internet
Author: User
PHP recursive function when using return will not be able to correctly return to the desired situation, if you do not understand the reasons, it is difficult to find the wrong, the following specific examples to illustrate:

function test ($i) {    $i-=4;    if ($i <3) {        return $i;    } else{        Test ($i);}    } echo Test (30);

This code does not seem to be a problem, if you do not run the estimate you do not think he has any problems, timely operation to find that there are problems you do not necessarily know where there is a problem, but in fact, the function of the else inside is problematic. The result of executing 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:

function test ($i) {    $i-=4;    if ($i <3) {        return $i;    } else{        return Test ($i);//Add return, let function return value    }}echo test (30);

Related articles
How does php recursive function work? Typical examples of PHP recursive functions
PHP Recursive function Introduction to the array correlation function in PHP
Analysis of the use of return value of PHP recursive function

  • 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.