How can I filter an associative array that takes one or more characters and matches that against the array keys using regex, and then returns the matched array?
Like we query the database:
select all from table-name where username LIKE %search%
I want to do the same with associative arrays.
I need to send an ajax call for every keyup
event on the clientside. The server then takes that key, filters the array and sends back the results.
Considering that you have an array like this:
$haystack = [
'foo' => 123,
'foobar' => 234,
'foobarbaz' => 345,
'barbazfoo' => 456,
'foobaz' => 567,
];
You can filter the array by foobar
key like this:
$matches = preg_grep('/foobar/', array_keys($haystack))
// => [
// 1 => "foobar",
// 2 => "foobarbaz",
// ]
Now that you have the keys, you just need to reduce the original array:
array_intersect_key($haystack, array_flip($matches))
// => [
// "foobar" => 234,
// "foobarbaz" => 345,
// ]
There are so many ways to do this. As reactivity is a concern in your case, you need to find the most performant way to do this.
To wrap it up as a function:
function array_key_lookup($haystack, $needle)
{
$matches = preg_grep("/$needle/", array_keys($haystack));
return array_intersect_key($haystack, array_flip($matches));
}