How to find array key which has value containing certain string

103 views Asked by At

I know i can do it like this when i'm looking for value inside array.

$example = array('example','One more example','last example');
$searchword = 'last';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });

However I'm wanting to do something like this but for this example:

$example = array( "first" => "bar", "second" => "foo", "last example" => "boo");
$searchword = 'last';

How can I change this to get the key value which contains searchword instead of the value?

$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
2

There are 2 answers

2
Sahil Gulati On BEST ANSWER

You can try this one. Here we are using array_flip, array_keys and preg_grep

Solution 1:

Try this code snippet here

<?php
$searchword = 'last';
$example = array( "first" => "bar", "second" => "foo", "last example" => "boo");
$result=array_flip(preg_grep("/$searchword/",array_keys($example)));
print_r(array_intersect_key($example, $result));

Solution 2: (Since PHP 5.6) A good recommendation by @axiac

Try this code snippet here

<?php
ini_set('display_errors', 1);
$searchword = 'last';
$example = array( "first" => "bar", "second" => "foo", "last example" => "boo");
$example=array_filter($example,function($value,$key) use($searchword){
    return strstr($key, $searchword);
},ARRAY_FILTER_USE_KEY);
print_r($example);
1
abderrahime sanadi On

You can use the function array_keys which get you only the key of the array $example

$matches = array_filter(array_keys($example), function($var) use ($searchword) { 
return preg_match("/\b$searchword\b/i", $var); });