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?
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.
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.
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.
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
# )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With