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 Courses
php Courses
php Courses
Using PHP max() Function: Syntax, Usage, and Examples

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

Comparing strings

Strings are compared lexicographically:

echo max("apple", "banana", "cherry"); // outputs cherry
echo max("dog", "cat", "elephant"); // outputs elephant

Comparing 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 6

Comparing 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 5

Comparing empty arrays

If an empty array is supplied, max() returns negative infinity (-INF):

$emptyArray = array();
echo max($emptyArray); // outputs -INF

Comparing with null values

Null values are ignored, and the maximum of the remaining values is returned:

echo max(1, null, 3); // outputs 3

Comparing 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 30

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

data comparisonmax-functionphp-tutorial
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.