Dales Vu Dales Vu - 1 month ago 6
PHP Question

Finding max value in array using recursion in PHP

I know how to use loop to do this simple problem, but I want to play more with recursion. I trying to find max value in array using recursion with PHP. My basic idea is compare the first value of the array with the maximum value of the new array (made by remove the first value of the given array):

function find_max($arr)
{
if ($arr = [])
{
return 0; // base case
} else
{
if ($arr[0] > find_max(rest_of($arr)))
{
return $arr[0];
} else
{
return find_max(rest_of($arr));
}
}
}

function rest_of($arr)
{
unset($arr[0]); // remove the first value of the array
$arr = array_values($arr); // re-index the array
return $arr;
}


But when I run, it seems that it has infinite loop. "Undefined offset: 0"
Can anyone help me?

Answer

The problem is because of your base condition here,

if($arr = []){ ...

= is an assignment operator, not comparison operator. What you need here is a comparison operator ==. So it should be,

if($arr == []){

Furthermore, you can change your base condition like this way,

if(count($arr) == 1){
    return $arr[0]; // base case
}

So your find_max() function should be like this:

function find_max($arr){
    if(count($arr) == 1){
        return $arr[0]; // base case
    }
    if ($arr[0] > find_max(rest_of($arr))){
        return $arr[0];
    } else{
        return find_max(rest_of($arr));
    }
}
Comments