Asked  7 Months ago    Answers:  5   Viewed   25 times

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci totally lost me!

Thank you in advance ;-) Also how often do you use them in web development?

 Answers

50

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
Tuesday, June 1, 2021
 
relipse
answered 7 Months ago
90

The main thing you needed (as you said) is to build the arrays to pass the data back. This code will build a sub element if there are more elements to add or just set the return value to the item if nothing is found. Not sure if the format of the output is exactly what you are after, but you may be able to work with it.

function getPre($array, $char) {
    $graph = [];
    foreach ($array as $pre) {
        if ( $pre[2] == $char ) {
            $graph[$pre] = getPre($array, $pre[0]) ?: $pre;
        }
    }

    return $graph;
}

Note than rather than having to use substr() to extract a character, you can use the string as an array and [2] is the 3rd character.

This outputs...

Array
(
    [k-z] => Array
        (
            [e-k] => Array
                (
                    [c-e] => Array
                        (
                            [a-c] => a-c
                        )

                )

        )

    [q-z] => Array
        (
            [x-q] => x-q
        )

)

To output the codes as strings, I've processed the result of the above function using iterators. The idea being to start at the leaf nodes and then to track back (using getSubIterator()) to the base of the tree...

$graph = getPre($items, $end);
$objects = new RecursiveIteratorIterator( new RecursiveArrayIterator( $graph ), RecursiveIteratorIterator::LEAVES_ONLY );
foreach ( $objects as $name => $object )    {
    $path = $object;
    for ( $depth = $objects->getDepth() - 1; $depth >= 0; $depth-- ) {
        $path .= ",".$objects->getSubIterator( $depth )->key();
    }
    echo $path.PHP_EOL;
}

Which outputs...

a-c,c-e,e-k,k-z
x-q,q-z
Wednesday, March 31, 2021
 
Besnik
answered 9 Months ago
33

EDIT I added a pull request with a fix: https://github.com/PHPOffice/PHPExcel/pull/251

This happens when you try to duplicate cell's style to the same cell; Take a look at this:

$phpe = new PHPExcel();
$sheet = $phpe->createSheet();

$sheet->setCellValue('A1', 'hi there') ;
$sheet->setCellValue('A2', 'hi again') ;

$sheet->duplicateStyle($sheet->getStyle('A1'), 'A2');

$writer = new PHPExcel_Writer_Excel2007($phpe);
$writer->save('./test.xlsx');

It will work just fine. BUT if I add another line like this:

$sheet->duplicateStyle($sheet->getStyle('A1'), 'A1');

then bang, infinite recursion starts after calling the save method

To fix your code, you should modify this part:

$sheet->duplicateStyle((($level == 0) ?  $this->styles['category'] : $this->styles['subcategory']), Cell::NUMBER . $row);

To something along the lines of:

$style = ($level == 0) ?  $this->styles['category'] : $this->styles['subcategory'];
$targetCoords = Cell::NUMBER . $row;
if($style->getActiveCell() != $targetCoords) {
    $sheet->duplicateStyle($style, $targetCoords);
}
Saturday, May 29, 2021
 
rblarsen
answered 7 Months ago
74

Recursive functions are OK - but dangerous if you aren't sure you know what you are doing. If there is any chance that a function will end up in a recursive loop (where it keeps calling itself over and over) you will either time out, run out of memory or cause a zombie apocalypse.

Think of recursive calls as a really, really sharp knife - in the hands of an experienced chef, it's a match made in heaven, in the hands of the dishwasher, it is a lost finger waiting to happen.

PHP tries to play nice, and limits a recursive depth to 100 by default (though this can be changed) but for almost all cases, if your recursive depth gets to 100, the accident has already happened and PHP reacts by stopping any additional pedestrians from wandering into traffic. :)

Saturday, May 29, 2021
 
njai
answered 7 Months ago
22

add these code into the top of your script

@set_magic_quotes_runtime(false);
ini_set('magic_quotes_runtime', 0);
Wednesday, August 18, 2021
 
Warrior
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share