skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER
    foreach(array_filter($pets, 
        fn($v) => $v["species"]=="Dog") as $row) echo $row["name"];
    

    or, replacing the foreach loop with implode() and array_column():

    echo implode(", ", 
            array_column(
                array_filter($pets, fn($v) => $v["species"]=="Dog"), 
                "name")
        );
    

    The latter would I guess be more strictly functional.


  2. 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"]
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search