Home » Php » php – Check if array key exists that matches regex

php – Check if array key exists that matches regex

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a quick(er) way to check if an array key exists that matches a pattern? My goal is to use the value of a key that starts with “song_“, regardless of how it ends.

currently I’m doing this:

foreach($result as $r){
   // $r = array("title"=>'abc', "song_5" => 'abc')
   $keys = array_keys($r);
   foreach($keys as $key){
       if (preg_match("/^song_/", $key) {
          echo "FOUND {$r[$key]}";
       }
   }           
}

Is there a way to to a preg_match across arrays, or is foreach through array_keys the most native way to do that?

How to&Answers:

How about using preg_grep:

$keys = ['song_the_first', 'title', 'song_5'];
$matched = preg_grep('/^song_/', $keys);
# print_r($matched)
#
# Array
# (
#     [0] => song_the_first
#     [2] => song_5
# )