Considerations for using return in php recursive functions

Source: Internet
Author: User
When using return in php recursive functions, you may encounter situations where the desired value cannot be returned correctly. The following is an example.

When using return in php recursive functions, you may encounter situations where the desired value cannot be returned correctly. The following is an example.

When using return in php recursive functions, the expected value cannot be returned correctly. If you do not understand the cause, it is difficult to find out the error, the following is an example:

The Code is as follows:


Function test ($ I ){
$ I-= 4;
If ($ I <3 ){
Return $ I;
} Else {
Test ($ I );
}
}
Echotest (30 );


This Code seems to be okay. If you don't run it, you probably won't think there is any problem with it. If you run it in time, you may not know where there is a problem, but in fact there is a problem in the else of this function. The execution result in this Code does not return a value. Therefore, even if the condition $ I <3 is met, the return $ I function does not return a value. Therefore, the above PHP recursive functions can be modified as follows (for more PHP tutorials, visit the code home ):

The Code is as follows:


Function test ($ I ){
$ I-= 4;
If ($ I <3 ){
Return $ I;
} Else {
Return test ($ I); // Add return to let the function return values.
}
}
Echotest (30 );

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.