How to get key of minimum value in given array in PHP

On working with huge data, sometimes you might needed to get the key of minimum value of given array. You can do it with your custom function. Below is the example I found very simple and easy.

<?php

$arr = [
    0 => 3425,
    1 => 1567,
    2 => 785,
    3 => 4181
];

$min_val_id = min(array_keys($arr, min($arr)));
echo($min_val_id); // 2

So what the above code does is first check the minimum value from array using min() function and array_keys() function returns array of key. Then outer min() function returns single value of that key which is key of minimum value from give array.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment