PHP max() Function
The max() function is an inbuilt function in PHP, used to find the numerically maximum value in an array or the numerically maximum value of several specified values.
Syntax
max(array_values)
or
max(value1, value2, ...)
Parameters
This function accepts two different types of arguments which are explained below:
- array: You can pass a single array to the max() function to find the maximum value within the array.
- value1, value2, value3, ...: A comma-separated list of values or variables that you want to compare. These values can be of different types (integers, floats, strings, etc.).
Return Value
The max() function returns the numerically maximum value from the given values or from the array.
Find Maximum Value using max() Function with Multiple Values
The max() function can be used with multiple values (or variables) to find the largest one. PHP compares these values and returns the highest value.
Example 1: Comparing Integers
<?php
echo (max(12, 4, 62, 97, 26));
?>
Output
97
Example 2: Comparing Floats
<?php
// Comparing Float Values
echo max(3.5, 7.2, 6.8);
?>
Output
7.2
Example 3: Comparing Strings
When comparing strings, PHP uses the ASCII values of the characters to determine the "largest" string.
<?php
// Comparing Strings
echo max("Apple", "Banana", "Cherry");
?>
Output
Cherry
Using the max() Function with an Array
The max() function can also be used to find the maximum value in an array. If the array contains mixed data types (e.g., numbers and strings), PHP will compare the values based on their types and return the largest value.
Example 1: Finding the Maximum Value in a Numeric Array
<?php
// Integer Array
$numbers = [10, 50, 30, 70, 20];
// Find the Largest Value
echo max($numbers);
?>
Output
70
Example 2: Finding the Maximum Value in an Array with Mixed Types
<?php
// Array with Mixed Data Types
$values = [3, "20", 5.5, "Apple", 15];
// Find the Maximum Value
echo max($values);
?>
Output
15