How to Get Maximum Key Value of Array in PHP

AuthorSumit Dey Sarkar

Pubish Date27 Jan 2024

categoryPHP

In this tutorial, we will learn how to get maximum key value of array in PHP.

How to Get Maximum Key Value of Array in PHP

How to find the maximum value of an array in PHP

You can find the maximum value of an array using the max() function. Here's an example:

<?php
// Your array
$myArray = array(10, 5, 8, 2, 15);

// Get the maximum value
$maxValue = max($myArray);

// Display the result
echo "The maximum value in the array is: " . $maxValue;
?>

In this example, the max() function takes an array as an argument and returns the maximum value in that array. You can replace the values in $myArray with your own array of numbers.

If your array contains associative keys and you want to find the maximum value based on the keys, you can use the max() function with the array_values() function to get the values before finding the maximum. Here's an example:

<?php
// Your associative array
$myAssocArray = array(
    'key1' => 10,
    'key2' => 5,
    'key3' => 8,
    'key4' => 2,
    'key5' => 15
);

// Get the maximum value
$maxValue = max(array_values($myAssocArray));

// Display the result
echo "The maximum value in the associative array is: " . $maxValue;
?>

In this example, array_values() is used to extract the values from the associative array before finding the maximum value.

Comments 0

Leave a comment