Filtering Arrays Without Using Loops in PHP

Have you ever had the need to filter through an existing array and create a new array based on your filter for your application to process? I’m sure the majority of you have, and personally I find it a bit tedious having to create a loop each time I need to filter through the data I need.

PHP has a built in function called array_filter that allows you to filter through your arrays without the need for a loop. Personally, this approach feels much cleaner to me and simpler to comprehend.

Example

Let’s say we have an array of People, with different names and ages. For our application though, we’d want to get a list of all People age 21 or above.

First let’s create our Person class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?php

classPerson

{

private$name;

private$age;

publicfunction__construct(string$name,int$age)

{

$this->name=$name;

$this->age=$age;

}

publicfunctionname():string

{

return$this->name;

}

publicfunctionage():int

{

return$this->age;

}

}

Now let’s create our array of people.

1

2

3

4

5

6

7

8

9

10

11

<?php

$people=[

newPerson('Frank',29),

newPerson('Sarah',28),

newPerson('Michael',27),

newPerson('James',20),

newPerson('Stephanie',21),

newPerson('Josh',19),

];

Now that we have our array set up. Let’s see how we may have solved this with loops.

Tags

About This Blog

I'm writing this blog in order to share what I'm learning with the world. Since you learn best by teaching others and writing things down, I figured this would be the best way to really tackle any new technologies I plan on learning. I hope this blog will help you as much as it will benefit me.