Home > Mobile >  How to get the largest value from an array PHP
How to get the largest value from an array PHP

Time:10-28

I need a PHP code to find the largest number from the array. I have the below set of data. I need to find the largest value from this. In this example, the largest value is 22-221. How can I do this? Thanks.

  array:8 [
    0 => null
    1 => "22-115"
    2 => "AAAAAAAAA"
    3 => "22-001"
    4 => "22-221"
    5 => "22-004"
    6 => "22-023"
    7 => "22-002"
  ]

I have tried sort() but it not works as expected.

CodePudding user response:

The usort() function allows you to specify your own comparison mechanism. Here, you could provide a function to strip non-digit characters and then compare the resulting integer.

$array = [
    null,
    "22-115",
    "AAAAAAAAA",
    "22-001",
    "22-221",
    "22-004",
    "22-023",
    "22-002",
];

function compare($a, $b)
{
    $intA = preg_replace('/\D/', '', $a);
    $intB = preg_replace('/\D/', '', $b);
    if ($intA > $intB) {
        return -1;
    }
    if ($intA < $intB) {
        return 1;
    }
    return 0;
}

usort($array, 'compare');
print_r($array);

This yields:

Array
(
    [0] => 22-221
    [1] => 22-115
    [2] => 22-023
    [3] => 22-004
    [4] => 22-002
    [5] => 22-001
    [6] =>
    [7] => AAAAAAAAA
)

Then you can just take the first element:

$max = $array[0];

Or, the same thing inline:

usort($array, fn($a, $b) => preg_replace('/\D/', '', $b) <=> preg_replace('/\D/', '', $a));
$max = $array[0];

CodePudding user response:

$array = [
    null,
    "22-115",
    "AAAAAAAAA",
    "22-001",
    "22-221",
    "22-004",
    "22-023",
    "22-002",
];

$max = max(filter_var_array($array, FILTER_SANITIZE_NUMBER_INT));
echo $max;  //22-221

Demo: https://3v4l.org/h5LGF

  • Related