amiroperator amiroperator - 5 months ago 24
PHP Question

PHP groupBy array search

I want to search in an array like SQL queries and I have no idea how to do that.
Here is my array:

$array = array(
'app' => 'apple',
'ban' => 'banana',
'lem' => 'lemon',
'ora' => 'orange',
);


when I search for
%an%
should return this:

$array = array(
'ban' => 'banana',
'ora' => 'orange',
);


and when I search for
%or%
should return this:

$array = array(
'ora' => 'orange'
);


I mean search in both key and value of array

Answer

To search in both keys and values, I think the easiest way is to use a foreach loop.

$term = 'an';   // define your search term

foreach ($array as $key => $value) {
    // check in both key and value using strpos
    if (strpos($key, $term) !== false || strpos($value, $term) !== false) {
        $result[$key] = $value;   // add to search result if found
    }
}
Comments