Backend Development 3 min read

Using PHP’s max() Function to Find the Largest Value

This article explains how PHP’s max() function works with both scalar values and arrays, describes its parameters and return value, and provides multiple code examples demonstrating how to retrieve the greatest element in various scenarios.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP’s max() Function to Find the Largest Value

The max() function in PHP returns the highest value among its arguments. When a single array is passed, it returns the largest element of that array; when multiple scalar values are supplied, it compares them and returns the greatest.

Signature

mixed max(array $values)

Parameters

values : an array containing multiple comparable values.

value1, value2, ... : any comparable scalar values (integers, strings, floats, etc.).

Return value

The function returns the maximum value among the provided arguments.

Examples

<?php
// Example with scalar values
echo max(1, 3, 5, 6, 7); // 7

// Example with a single array
echo max(array(2, 4, 5)); // 5

// Mixing integers and strings (string cast to int becomes 0)
echo max(0, 'hello'); // 0
echo max('hello', 0); // hello

// String compared with integer
echo max('42', 3); // '42'

// Negative number vs string
echo max(-1, 'hello'); // hello
?>

When multiple arrays of different lengths are compared, max() evaluates them element‑by‑element from left to right, returning the first array that is greater. Example:

$val = max(
    array(2, 2, 2),
    array(1, 1, 1, 1)
); // returns array(2, 2, 2)

$val = max(
    array(2, 4, 8),
    array(2, 5, 7)
); // returns array(2, 5, 7)

If both an array and a non‑array are supplied, the array is always considered larger, and the function returns the array.

BackendProgrammingphparraycomparisonmax-function
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

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