Reputation: 1934
I have a PHP array that looks like this:
array (size=3)
'CA,Santa Barbara' =>
array (size=2)
'state' => string 'CA' (length=2)
'city' => string 'Santa Barbara' (length=13)
'KS,Andover' =>
array (size=2)
'state' => string 'KS' (length=2)
'city' => string 'Andover' (length=7)
'KS,Wichita' =>
array (size=2)
'state' => string 'KS' (length=2)
'city' => string 'Wichita' (length=7)
I need to return all the array members who have the values:
state => 'KS'
I am needing to get an array back that looks like this:
array (size=2)
'KS,Andover' =>
array (size=2)
'state' => string 'KS' (length=2)
'city' => string 'Andover' (length=7)
'KS,Wichita' =>
array (size=2)
'state' => string 'KS' (length=2)
'city' => string 'Wichita' (length=7)
Is there a PHP array function that does this? I have found array_search() but that only returns the first match. I need ALL matches.
Upvotes: 4
Views: 273
Reputation: 19764
You could use array_filter()
to remove all unneeded values:
$array = [
'CA,Santa Barbara' => ['state' => 'CA', 'city' => 'Santa Barbara'],
'KS,Andover' => ['state' => 'KS', 'city' => 'Andover'],
'KS,Wichita' => ['state' => 'KS', 'city' => 'Wichita'],
];
$state = 'KS';
$out = array_filter($array, fn($v) => $v['state'] == $state);
print_r($out);
Outputs:
Array(
[KS,Andover] => Array(
[state] => KS
[city] => Andover
)
[KS,Wichita] => Array(
[state] => KS
[city] => Wichita
)
)
You can also use type hinting to get a better data flow control:
$out = array_filter($array, fn(array $v): bool => $v['state'] == $state);
# ^ ^
# | |
# | array_filter's callback returns
# | a boolean (true to keep,
# | false to remove).
# |
# each elements of the $array
# are arrays.
Before PHP 7.4, (without arrow functions), you have to use the keyword use
to pass the $state
variable to the anonymous function:
$state = 'KS';
$out = array_filter($array, function($v) use ($state) {
return $v['state'] == $state;
});
print_r($out);
Upvotes: 10