user3291017
user3291017

Reputation: 47

My first recursive function not calling itself correctly?

This piece of code is supposed to find the highest value of a group, no matter how many nested arrays there are. I am trying, for the first time, to create a function that will call itself every time the event happens, that's the value is an array. Why is it saying my variables are not defined?

<?php
    $arr = array("1", "2", array("3", "4"));

    function getitMax($arr){
        foreach ($arr as $value){
            if(is_array($value)){
                getitMax($value);
            } else {
                $max_array=array($value);
            }
        }
    }
    getitMax($arr);

    echo max($max_array);
?>

Upvotes: 0

Views: 77

Answers (2)

kwelsan
kwelsan

Reputation: 1219

Try below code might be a bit lengthy approach:

<?php   
class GetMax {
    private $max_array = '';
    public function getitMax($arr){     
        foreach ($arr as $value){
            if(is_array($value)){
                $this->getitMax($value);
            } else {
                $this->max_array[] = $value;
            }
        }       
        return max($this->max_array);
    }
}

$m = new GetMax();
$arr = array("1", "2", array("3", "4"));
echo $m->getitMax($arr);
?>

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

Your problem is that you're just calling your function here:

if(is_array($value)){
        getitMax($value);

}

-but doing nothing with it's result. And also your function has no return - i.e. result will be null. To fix this, do something like:

function  getitMax($arr)
{
    $max = null;
    foreach($arr as $value)
    {
        if(is_array($value))
        {
            $current = getitMax($value);
        }
        else 
        {
            $current = $value;
        }
        //assign max to current if current is larger:
        if($current>$max)
        {
           $max = $current;
        }
    }
    return $max;
}

Upvotes: 1

Related Questions