Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array key exists that matches regex

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?

like image 389
d-_-b Avatar asked Aug 10 '14 06:08

d-_-b


People also ask

How to check if array key exist?

Answer: Use the PHP array_key_exists() function You can use the PHP array_key_exists() function to test whether a given key or index exists in an array or not. This function returns TRUE on success or FALSE on failure.

How to check array key value in PHP?

The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.

How to check if an array exists PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 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
# )
like image 95
falsetru Avatar answered Oct 08 '22 05:10

falsetru