Using PHP max() Function: Syntax, Usage, and Examples
This article explains PHP's max() function, covering its syntax, how to compare integers, floats, strings, arrays, objects, and handling of empty values, with clear code examples for each case in different scenarios.
PHP's max() function returns the highest value among a set of values. It accepts any number of arguments, which can be integers, floats, strings, arrays, or objects.
Basic Syntax
The function is called as max(value1, value2, value3, ...), where each value is a parameter to be compared.
Usage
Comparing integers and floats
Examples:
echo max(1, 2, 3); // outputs 3
echo max(2.3, 4.5, 1.2); // outputs 4.5Comparing strings
Strings are compared lexicographically:
echo max("apple", "banana", "cherry"); // outputs cherry
echo max("dog", "cat", "elephant"); // outputs elephantComparing mixed types
When mixed types are provided, strings are converted to numbers for comparison:
echo max(1, 2, "3"); // outputs 3
echo max("4", 5, 6); // outputs 6Comparing arrays
When an array is passed, the function returns the largest element in the array:
$numbers = array(1, 2, 3, 4, 5);
echo max($numbers); // outputs 5Comparing empty arrays
If an empty array is supplied, max() returns negative infinity (-INF):
$emptyArray = array();
echo max($emptyArray); // outputs -INFComparing with null values
Null values are ignored, and the maximum of the remaining values is returned:
echo max(1, null, 3); // outputs 3Comparing objects
Objects can be compared by extracting comparable properties, such as age:
class Person {
public $age;
function __construct($age) {
$this->age = $age;
}
}
$person1 = new Person(20);
$person2 = new Person(30);
$person3 = new Person(25);
echo max($person1->age, $person2->age, $person3->age); // outputs 30Summary
The max() function in PHP can compare integers, floats, strings, arrays, and object properties, handling empty arrays and null values appropriately, and always returns the greatest value according to the type‑specific comparison rules.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
