1

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); });
YaBCK
  • 2,949
  • 4
  • 32
  • 61
  • you could generate an array of the array keys using array_keys and do the search on that, and use matched keys to retrieve their vals from the original array. – flauntster Sep 11 '17 at 08:56
  • Take a look [here](https://stackoverflow.com/questions/5808923/filter-values-from-an-array-similar-to-sql-like-search-using-php) – Michel Sep 11 '17 at 08:57
  • @Michel I've already got it searching the values, I'm wanting it based on the `key` – YaBCK Sep 11 '17 at 08:58
  • 2
    Since PHP 5.6, if you pass `ARRAY_FILTER_USE_BOTH` as the third argument of [`array_filter()`](http://php.net/manual/en/function.array-filter.php) it passes both the value and the key to the callback function. – axiac Sep 11 '17 at 08:59
  • Possible duplicate of [PHP: How to use array\_filter() to filter array keys?](https://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys) – Progrock Sep 11 '17 at 09:21

2 Answers2

1

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); });
1

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);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42