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?