php - finding keys in an array that match a pattern

前端 未结 6 601
刺人心
刺人心 2020-12-10 11:13

I have an array that looks like:

 Array ( [2.5] => ABDE [4.8] => Some other value ) 

How would I find any key/value pair where the k

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 12:00

    Old question, but here's what I like to do:

    $array = [ '2.5' => 'ABDE', '4.8' => 'Some other value' ];
    

    preg_grep + array_keys will find all keys

    $keys = preg_grep( '/^2\.\d/i', array_keys( $array ) );
    

    You can add array_intersect_key and array_flip to extract a slice of the array that matches the pattern

    $vals = array_intersect_key( $array, array_flip( preg_grep( '/^2\.\d/i', array_keys( $array ) ) ) );
    

提交回复
热议问题