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:
<code>echo max(1, 2, 3); // outputs 3
echo max(2.3, 4.5, 1.2); // outputs 4.5</code>Comparing strings
Strings are compared lexicographically:
<code>echo max("apple", "banana", "cherry"); // outputs cherry
echo max("dog", "cat", "elephant"); // outputs elephant</code>Comparing mixed types
When mixed types are provided, strings are converted to numbers for comparison:
<code>echo max(1, 2, "3"); // outputs 3
echo max("4", 5, 6); // outputs 6</code>Comparing arrays
When an array is passed, the function returns the largest element in the array:
<code>$numbers = array(1, 2, 3, 4, 5);
echo max($numbers); // outputs 5</code>Comparing empty arrays
If an empty array is supplied, max() returns negative infinity (-INF):
<code>$emptyArray = array();
echo max($emptyArray); // outputs -INF</code>Comparing with null values
Null values are ignored, and the maximum of the remaining values is returned:
<code>echo max(1, null, 3); // outputs 3</code>Comparing objects
Objects can be compared by extracting comparable properties, such as age:
<code>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 30
</code>Summary
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.
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.