简体   繁体   中英

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?

This should work for you:

Here I just use array_filter() combined with stripos() to search through each array key if it contains the search value.

<?php

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

    $search = "Phor";
    $arr = array_filter($array, function($k)use($search){
        return stripos($k, $search) !== FALSE;
    }, ARRAY_FILTER_USE_KEY);

    print_r($arr);

?>

output:

Array
(
    [Phorce] => 123
) 

Before someone says, that it doesn't work: You need PHP 5.6, so if you don't have that upgrade!

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

Use Below code to get Response:

Demo Code

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

var_export(
    array_filter(
        $values,
        function($haystack ) {
          if (is_numeric(strpos($haystack, 'Phorce'))) {
            return $haystack;
          } 
        },
        ARRAY_FILTER_USE_KEY
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM