What in Layman'S Terms Is a Recursive Function Using PHP

What in layman's terms is a Recursive Function using PHP

Laymens terms:

A recursive function is a function that calls itself

A bit more in depth:

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n) {
if ($n === 0) { // our base case
return 1;
}
else {
return $n * fact($n-1); // <--calling itself.
}
}

In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.

Although I cannot compete with the directory example, I hope this helps somewhat.

(4/20/10) Update:

It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,

  • Understanding basic recursion

What is a recursive function in PHP?

Recursive functions in php are no different than in other languages. It's simply a function that calls itself. There's no real need to show examples of recursion in php because it's just so simple. Take a look at the Wikipedia article. And here's the famous fibonacci numbers example in php.

PHP recursive function

The order of execution is this:

if 1 <= 10 true call getX(1)
if 2 <= 10 true call getX(2)
if n <= 10 call getX(n)
if 11 <= 10 false
// now go all the way back to the getX(0)
return and echo 11;
return and echo n;
return and echo 2;
return and echo 1;

Visualized on your code:

recursion explained

Explained in words:

  • Until $count is 11, it will keep calling getX() with $count (1+2)
  • Once your if is false it will start processing the remaining code, e.g. it will return $count (3)
  • This then gets assigned and echo'ed as $countTemp (4+5)
  • Then $count is returned again until it's back at the original callee. (5 back to 4)

How to create a recursive function in php?

You just need to pass the $result as a parameter to the function, and add to it little by little.

UPD: I've tweaked the function's code a little regarding your reply. Please refer to this example:

$commentsArr = [
[
'text' => 'commentText1',
'childs' => [
[
'text' => 'commentTextC1'
],
[
'text' => 'commentTextC2'
],
[
'text' => 'commentTextC3',
'childs' => [
[
'text' => 'commentTextC3.1'
],
[
'text' => 'commentTextC3.2'
],
]
],
]
],
[
'text' => 'commentText2'
]
];


function display_comments($commentsArr, $level = 0, $result = ['html' => ''])
{
foreach ($commentsArr as $commentInfo) {
$widthInPx = ($level + 1) * 30;
$result['html'] .= '<div data-test="' . $widthInPx . '">'.$commentInfo['text'].'</div>';
if (!empty($commentInfo['childs'])) {
$result = display_comments($commentInfo['childs'], $level + 1, $result);
}
}
return $result;
}

How can a function call itself in PHP?

You may want to read about recursive functions.

A recursive function is a function that calls itself

This function takes some argument and checks if it has an alias. If it does, it calls itself again and checks if found alias has an alias etc.

Recursive function in simple english

Three words - It Calls Itself.

php recursive function in class

To be perfectly honest, "it no longer works" isn't a helpful metric by which to assist you in debugging your problem. Nor is "it works fine", since that doesn't tell us your definition of what works means to you. More precisely, these statements don't tell us what you expected the code to do that it's not doing, or what the code is doing that you did not expect.

To me this code is doing exactly what you've told it to do and the result of both a function as well as a class method (using the same code) are identical... See the working 3v4l pastebin here.

However, my guess is that your expectations may be different from what this code actually does. Specifically, this function will return at the very first match of the $needle in the $haystack. Such that the following array, returns 0 (_that is with a needle of 'foo').

$haystack = ['foo', ['foo', 'bar']];

It will also return only the key of the outer-most array in the $haystack. Meaning, the following array returns 0 as the key. Even though the actual match is in $haystack[0][1][2]

$haystack = [['bar',['quix','baz','foo'],'baz'],'quix'];

So depending on what you expected (the inner-most key, or the outer-most key), you may believe this function doesn't work.

So you'll need to clarify exactly what you want the code to do and provide some reproducible example of what didn't work (and that includes the data used or arguments provided to the function).


EDIT:

Hey, I'm glad you figured it out. Here are just a few suggestions to maybe help you refactor this code slightly as well...

So since you're looking for the existence of the needle in any part of the array and don't actually care about the key, you may want to make your intent more obvious in the logic.

So for example, always return a boolean (true on success and false on failure) rather than return false on failure and the key on success. This makes checking the function's result easier and clearer from the caller's perspective. Also, consider naming the function to describe it's intent more clearly (for example: in_array_recursive rather than recursive_array_search since we're not actually intent on searching the array for something, but proving that something is actually in the array). Finally, consider avoiding multiple return points in the same function as this makes debugging harder.

So a cleaner way to write the same code might be something like this:

public function in_array_recursive($needle, $haystack, $strict = false) {

$result = false;

foreach($haystack as $value) {

if(!is_array($value)) {
$result = $strict ? $needle === $value : $needle == $value;
} else {
$result = $this->in_array_recursive($needle, $value, $strict);
}

if ($result) {
break;
}

}

return $result;

}

Now the caller simply does...

$arr = ['bar',['foo']];

if (in_array_recursive('foo', $arr)) {
/* 'foo' is in $arr! */
} else {
/* 'foo' is not in $arr... */
}

Making the code more readable and easier to debug. Notice you also don't have to use exact match if you wanted to add an optional argument for $strict at the end of the function there and also be more inline with in_array.

Anonymous recursive PHP functions

In order for it to work, you need to pass $factorial as a reference

$factorial = function( $n ) use ( &$factorial ) {
if( $n == 1 ) return 1;
return $factorial( $n - 1 ) * $n;
};
print $factorial( 5 );

How many times the last statement of a recursive function block gets executed?

I think you forgot the else.

<?php
function test() {
static $count = 0;

$count++;
echo $count."<br>";
if($count < 10) {
test(); // when this call is made, all the code bellow waits for it to return
} else {
echo "Count Value : ".$count--;
}
}

test();
?>

What happens is that every time you call test(), inside the if condition, the execution stops until the newly called test() returns. The test() function only returns when $count >= 10. which means that all hanging functions call will continue. What is a RECURSIVE Function in PHP?

Your code can be translated to something like this;

<?php
function test() {
static $count = 0;

$count++;
echo $count."<br>";
if($count < 10) {

static $count = 1;

$count++;
echo $count."<br>";
if($count < 10) {

static $count = 2;

$count++;
echo $count."<br>";
if($count < 10) {


// ... the code repeats until the point when $count = 9

} else {
echo "Count Value : ".$count--;
}

} else {
echo "Count Value : ".$count--;
}


} else {
echo "Count Value : ".$count--;
}
}

test();
?>


Related Topics



Leave a reply



Submit