filter php array by value using array_filter
filter php array by value using array_filter
I am trying to filter an array which will produce a drill down list.
This array is built from JSON.
My array looks like this
Array
(
[0] => Array
(
[make] => somemake
[model] => somemodel
[variant] => somevariant
[fuel] => somefuel
[vehicle] => somedetailedinfo
)
[1] => Array
(
[make] => somemake
[model] => somemodel1
[variant] => somevariant1
[fuel] => somefuel1
[vehicle] => somedetailedinfo
)
[2] => Array
(
[make] => somemake
[model] => somemodel2
[variant] => somevariant2
[fuel] => somefuel
[vehicle] => somedetailedinfo
)
[3] => Array
(
[make] => somemake1
[model] => somemodel3
[variant] => somevariant3
[fuel] => somefuel1
[vehicle] => somedetailedinfo
)
)
I would like to filter this array by the make $make
, which is set by the $_SERVER['QUERY_STRING']
.
$make
$_SERVER['QUERY_STRING']
The new array should contain all items with the make $make
.
$make
How do I do this using array_filter
?
array_filter
1 Answer
1
This is fairly straight-forward. Note that null coalesce (??
) is >= 7.0.
??
$make = $_GET['make'] ?? 'Chevy';
$vehicles = [[
'make' => 'Ford',
'model' => 'F-150',
'variant' => '4x4',
'fuel' => 'diesel',
'vehicle' => [range(1,3)],
],[
'make' => 'Ford',
'model' => 'Escort',
'variant' => 'XS',
'fuel' => 'gas',
'vehicle' => [range(1,3)],
],[
'make' => 'Chevy',
'model' => 'Cobalt',
'variant' => 'ES',
'fuel' => 'electric',
'vehicle' => [range(1,3)],
],[
'make' => 'Ford',
'model' => 'Explorer',
'variant' => '2x4',
'fuel' => 'gas',
'vehicle' => [range(1,3)],
],[
'make' => 'Mini',
'model' => 'Cooper',
'variant' => 'eTurbo',
'fuel' => 'electro-diesel',
'vehicle' => [range(1,3)],
],];
print_r(array_filter($vehicles, function($vehicle) use($make)
return $vehicle['make'] === $make;
));
Gives:
Array
(
[2] => Array
(
[make] => Chevy
[model] => Cobalt
[variant] => ES
[fuel] => electric
[vehicle] => Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
)
https://3v4l.org/B8T6v
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you, that works perfectly.
– James Littler
Sep 8 '18 at 21:50