Search code examples
phparraysarray-filter

How to find array key which has value containing certain string


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

Solution

  • 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);