Home > Back-end >  PHP Displaying an array_filtered result using foreach seems wrong - Is there a less dirty way?
PHP Displaying an array_filtered result using foreach seems wrong - Is there a less dirty way?

Time:10-14

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"]

?>
  • Related