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






Thank you, that works perfectly.

– James Littler
Sep 8 '18 at 21:50



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)