0

Whilst attempting to run the below code, my browser keeps responding with the below errors. How can I fix the below code, so these errors no longer present themselves?

To be clear, these errors appear only on the lines containing each of the below:

$high = $arr[$middleval+1];

$median = (($low+$high)/2);

Thanks

Code:

function median($arr)
{
    sort($arr);
    $count = count($arr); //count the number of values in array
    $middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
    if ($count % 2) { // odd number, middle is the median
        $median = $arr[$middleval];
    } else { // even number, calculate avg of 2 medians
        $low = $matches[0];
        $high = $arr[$middleval+1];
        $median = (($low+$high)/2);
    }
    return $median;
}

Errors:

Notice: Undefined offset: 0 in medium.php on line 9

Notice: Undefined variable: matches in medium.php on line 10

1 Answers1

0

Undefined offset is an out-of-bounds error: you're trying to fetch a value from the array that does not exist. E.g. if your array has two values, at indices 0 and 1, and $middleval equals 1, $arr doesn't have a value at $middleval + 1, i.e. $arr[2] is not set.

The second error message tells you that you're trying to use a variable $matches that is not defined.

You might want to look at this code review answer.

Community
  • 1
  • 1
Richard Turner
  • 12,506
  • 6
  • 36
  • 37