1.2.810. No Max On Empty Array

Using max() or min() on an empty array leads to a valueError exception.

Until PHP 8, max() and min() would return null in case of empty array. This might be confusing with actual values, as an array can contain null. null has a specific behavior when comparing with other values, and should be avoided with max() and sorts. Until PHP 8.0, a call on an empty array would return null, and a warning.

<?php

// Throws a value error
$a = max([]);

$array = [];
if (empty($array)) {
     $a = null;
} else {
     $a = max($array);
}


var_dump(min([-1,  null])); // NULL
var_dump(max([-1,  null])); // -1
var_dump(max([1,  null]));  // 1

?>

1.2.810.1. Suggestions

  • Check the content of the array before giving it to max() or min()

1.2.810.2. Specs

Short name

Structures/NoMaxOnEmptyArray

Rulesets

All, Changed Behavior, CompatibilityPHP80

Exakat since

2.5.2

Severity

Minor

Time To Fix

Quick (30 mins)

Changed Behavior

PHP 8.0 - More

Precision

High

Available in

Entreprise Edition, Exakat Cloud