Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Recursive function problem

Posted on 2006-11-19
Medium Priority
157 Views
function test(\$a) {
if (\$a > 10) {
if (\$a > 50) {
test(\$a-10);
}
else {
test(\$a-5);
}
}
else {
return \$a;
}
}

var_dump(test(100));

The above "example" function returns NULL.

Where am i going wrong?

0
Question by:fox_km
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2
• 2

LVL 49

Accepted Solution

Roonaan earned 500 total points
ID: 17974180
Use:

function test(\$a) {
if (\$a > 10) {
if (\$a > 50) {
return test(\$a-10);
}
else {
return test(\$a-5);
}
}
else {
return \$a;
}
}

-r-
0

Author Comment

ID: 17974221
Thank you.

Could you possibly explain why this works?

My logic was, you only want to return something if \$a is less then 10. I'm assuming the extra returns serve the purpose of halting the execution of the current function call. I had assumed that it wouldn't matter, as those calls do not return anything, therefore the original function call would only have a value returned when \$a <= 10. Is my understanding of recursive functions incorrect?
0

LVL 49

Expert Comment

ID: 17974232
Well you would either return it, or store the subfunctions call into a:

function test(\$a) {
if (\$a > 10) {
if (\$a > 50) {
\$a = test(\$a-10);
}
else {
\$a = test(\$a-5);
}
}
return \$a;
}

When you just call text(\$a - 10) and do nothing with its result, there is no sense in calling the function at all.

-r-
0

Author Comment

ID: 17974242
Okay, i understand. Thanks again.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called \$myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
###### Suggested Courses
Course of the Month9 days, 1 hour left to enroll