0

I have written below function to process an array but It is not returning me 1 thought It's output $input[0] returning me 1. don't understand why It is return NULL. Anything I return in that condition is return me NULL. Please explain me if anyone know. Thanks.

function endWithNumber($input)
{
    if (count(array_unique($input)) === 1) {        
        return $input[0];       
    }
    $maxVal = max($input);
    $maxKey = array_search($maxVal,$input);

    foreach ($input as $k => $v) {
        if ($maxKey != $k && $maxVal != $v) {
            $newVal  = ($maxVal - $v);
            $input[$maxKey] = $newVal;
            break;
        }
    }

    endWithNumber($input);
}

$input = array(6,10,15);  
var_dump(endWithNumber($input));
exit;
nurdglaw
  • 2,107
  • 19
  • 37
Jimit
  • 2,201
  • 7
  • 32
  • 66

1 Answers1

1

Your function returns nothing until your array count is 1. Because your return statement is in if block.

<?php
function endWithNumber($input)
{
    if (count(array_unique($input)) == 1) 
        return $input[0];       

    $maxVal = max($input);
    $maxKey = array_search($maxVal,$input);

    foreach ($input as $k => $v) 
    {
        if ($maxKey != $k && $maxVal != $v) 
        {
            $newVal  = ($maxVal - $v);
            $input[$maxKey] = $newVal;
            break;
        }
    }   

    return endWithNumber($input);
}

$input = array(6,10,15);  
var_dump(endWithNumber($input));

exit;   
?>
zkanoca
  • 9,664
  • 9
  • 50
  • 94