This is my array:-
$ header_menu = array(
['category'] => array(
'id' => 1,
'title' => 'Test Apple',
'slug' => 'category'
),
['how-to-do'] => array(
'id' => 1,
'title' => 'How to do',
'slug' => 'how-to-do'
)
)
The array is formed dynamically based on the data saved in the table. Due to that, sometimes the key can be 'category'
, sometimes it can be 'categories'
, based on what the admin has saved in the DB.
I need to fetch the key which has the substring 'categor'
, because this sequence of alphabets is present both in 'category'
& 'categories'
. By the following code, I can check if the 'categor'
substring is present in any of the key or not:-
if (preg_grep('/^categor/', array_keys($header_menu)))
{
}
One way is to run a loop like this:-
foreach($header_menu as $key => $row)
{
if(strpos($key, 'categor') !== false)
{
$catKey = $key;
}
}
However, I don't want to run a loop. Is there any other way to fetch the matching key?
You can use preg_grep if you do not want to loop through with array_keys() to get every key of your array and find all key matching given pattern.
$matchingKeys = array_keys($header_menu);
$matchingKeys = preg_grep('/'.'categor'.'\.\d/i', $matchingKeys);
If you know that you have only two options category/categories
, you can check if one of this fields exists in array:
if (isset($header_menu['category'])) {
$key = 'category';
} elseif (isset($header_menu['categories'])) {
$key = 'categories';
}
switch
variation which allows many options:
switch (true) {
case isset($header_menu['category']):
$key = 'category';
break;
case isset($header_menu['categories']):
$key = 'categories';
break;
}