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

Viewed 182

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...

3 Answers

I'm assuming you're learning, then there is nothing wrong with your solution. However, it's a but much code and can be done easier:

$highest = count($array) ? max($array) : 0;

I'll explain in steps:

  • $example = (statement) ? ifTrue : ifFalse. It is called a short if/else, this can be read as if(statement){ ifTrue } else{ ifFalse}.
  • Besides true and false, there is truthy and falsy. Simplefied: '>0' is truthy, '0' falsy. We can use that here:
    We use a count on $array. This is zero or higher.
    • If its higher -> its truthy -> the ifTrue will run. (max($array))
    • if its zero -> its falsy -> the ifFalse will return. (0 in this case)

Alternatively, your own code can be tweaked a bit and you have a working solution:

function getMaxArray($arr)
{
    //$i; php we dont declare variables like this.
    $max = 0; // <-- start with zero

    for ($i = 0; $i < $n; $i++) { // <-- start at first $array item
        if ($arr[$i] > $max) {
            $max = $arr[$i];
        }
    }
    return $max;
}

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;

Why reinvent the weel just lookup in php docs There is max function in php, that return largest number

max() — Find highest value

function getMaxArray($arr)
{
    return count($arr) ? max($arr) : 0;
}
Related