Skip to content
Advertisement

Filter array to retain all elements that have a key containing a searched string

I’m trying to do some predictive searching, and I am using preg_grep() as a way to get away from the LIKE in SQL.

I have the following array:

$values = array("Phorce" => 123, "Billy" => 234);

If I have Phorc I want all array elements (key and value), with a partial match of Phorc, so here Phorce => 123. Is this possible with preg_grep() ?

I have tried to use the following:

$result = preg_grep('~' . 'Phorce' . '~', $values);

How can I get my code to work as described above?

Advertisement

Answer

So you want to search the keys then?

$values = array("Phorce" => 123, "Billy" => 234);
$results = preg_grep('/Phor/', array_keys($values));

$arr = [];
foreach($results as $result) {
    $arr[$result] = $values[$result];
}

print_r($arr);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement