php - How to find array key which has value containing certain string -


i know can when i'm looking 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 example:

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

how can change key value contains searchword instead of value?

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

you can try one. here using array_flip, array_keys , preg_grep

solution 1:

try 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) recommendation @axiac

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

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -