We have an array of pets, with name and species defined.
$dogs = array_filter($pets,
fn($v) => $v["species"]=="Dog");
foreach($dogs as $row) echo $row["name"];
The foreach to display the result seems so wrong after such a beautiful arrow function.
Am I missing something?
CodePudding user response:
foreach(array_filter($pets,
fn($v) => $v["species"]=="Dog") as $row) echo $row["name"];
I think that's as simple as I'm getting it.
CodePudding user response:
https://www.php.net/manual/en/function.array-filter
<?php
$pets = array(
array('name'=>'Jack', 'species'=>'Dog'),
array('name'=>'Jina', 'species'=>'Cat')
);
function select_dog($var)
{
return $var["species"]=="Dog";
}
$dogs = array_filter($pets, 'select_dog');
foreach($dogs as $row) echo $row["name"]
?>