一千萬個為什麽

搜索

在關聯數組中查找最小值的鍵

在PHP中,假設你有一個像這樣的關聯數組:

$pets = array(
    "cats" => 1,
    "dogs" => 2,
    "fish" => 3
);

How would I find the key with the lowest value? Here, I'd be looking for cats.

有沒有一些內置的PHP函數,我錯過了這是什麽?如果有一個解決方案可以解釋幾個相同的值,那麽這也很好,如下所示:

$pets = array(
    "cats" => 1,
    "dogs" => 1,
    "fish" => 2
);

上面,我不介意它是否只是輸出; catsdogs

提前致謝。

最佳答案

array_keys is your friend:

$pets = array(
    "cats" => 1,
    "dogs" => 2,
    "fish" => 3
);
array_keys($pets, min($pets));  # array('cats')

P.S.: there is a dup here somewhere on SO (it had max instead of min, but I can distinctly remember it).

轉載註明原文: 在關聯數組中查找最小值的鍵