PHP Find Key of Minimum value in Given Array

  967 views   11 months ago 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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]