Check if associative array contains value, and retrieve key / position in array

前端 未结 3 1069
無奈伤痛
無奈伤痛 2021-01-02 18:05

I\'m struggling to explain what I want to do here so apologies if I confuse you.. I\'m just as confused myself

I have an array like so:

$foo         


        
3条回答
  •  有刺的猬
    2021-01-02 18:34

    Try something like this

    $foo = array(
        array('value' => 5680, 'text' => 'Red'), 
        array('value' => 7899, 'text' => 'Green'), 
        array('value' => 9968, 'text' => 'Blue'), 
        array('value' => 4038, 'text' => 'Yellow'),
    );
    
    $found = current(array_filter($foo, function($item) {
        return isset($item['value']) && 7899 == $item['value'];
    }));
    
    print_r($found);
    

    Which outputs

    Array
    (
        [value] => 7899
        [text] => Green
    )
    

    The key here is array_filter. If the search value 7899 is not static then you could bring it in to the closure with something like function($item) use($searchValue). Note that array_filter is returning an array of elements which is why I pass it through current

提交回复
热议问题