Skip to content
Advertisement

A PHP array function that receives positive numbers, returns the largest and returns 0 if array is empty

I’m trying to write a PHP function that receives an array of positive numbers and returns the largest number in the array. Though if the array is empty, it must return 0…

So far I have:

<?php
function getMaxArray($arr)
{
    $i;
    $max = $arr[0];

    for ($i = 1; $i < $n; $i++) {
        if ($arr[$i] > $max) {
            $max = $arr[$i];
        }
    }
    return $max;
}

But am not really sure how to incorporate the ‘else 0’, should I try to insert the for loop, inside of an ‘if first’ (couldn’t quite get it to work, upon my first try)?

Also, how would I make sure that the array only accepts positive numbers? I tried asking some friends and googling, but couldn’t find much on this…

Advertisement

Answer

Use max() for this, no need to overcomplicate the function:

$numbers = [103, 170, 210, 375, 315, 470, 255];

function getMaxArray($arr)
{
    if (empty($arr)) {
      return 0;
    } else {
      return max($arr);
    }
}

$largest = getMaxArray($numbers);

echo $largest;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement