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

前端 未结 16 1142
庸人自扰
庸人自扰 2020-11-22 05:50

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 to

16条回答
  •  悲哀的现实
    2020-11-22 06:29

    Walking through a directory tree is a good example. You can do something similar to process an array. Here is a really simple recursive function that simply processes a string, a simple array of strings, or a nested array of strings of any depth, replacing instances of 'hello' with 'goodbye' in the string or the values of the array or any sub-array:

    function replaceHello($a) {
        if (! is_array($a)) {
            $a = str_replace('hello', 'goodbye', $a);
        } else {
            foreach($a as $key => $value) {
                $a[$key] = replaceHello($value);
            }
        }
        return $a
    }
    

    It knows when to quit because at some point, the "thing" it is processing is not an array. For example, if you call replaceHello('hello'), it will return 'goodbye'. If you send it an array of strings, though it will call itself once for every member of the array, then return the processed array.

提交回复
热议问题