PHP array filter

PHP array filter

Last Updated on Feb 14, 2023

Array Filter

Array filter is a very useful function that gets 3 arguments


Array is the array that we are going to filter

Function is a callback function that returns true to keep the item or false to skip the item

Mode is by default 0 which means we use value of each item in our array in the function


There are 3 modes:

  1. 0 is the default which means the value of each item is given to the callback function
  2. ARRAY_FILTER_USE_KEY means use the key of each item as the function argument
  3. ARRAY_FILTER_USE_BOTH means use value and the key of each item as the function argument


Let’s see an example 

Here is our array

$array = [
   "twitter" => "Pratham",
   "Feedhive" => "Simon",
   "PHP" => "Amir",
   "Saas" => "Simon",
   "CSS" => "Pratham"

We want to filter the ones that have Pratham as the value

$filtered = array_filter($array, function ($value) {
   return $value == 'Pratham';
// Array ( [twitter] => Pratham [CSS] => Pratham )

Now let’s filter based on the key and filter the ones that have Feedhive as the key

$filtered = array_filter($array, function ($key) {
   return $key == "Feedhive";
// Array ( [Feedhive] => Simon )

Now let’s use both key and value and filter the ones that have value of Pratham or key of Feedhive

$filtered = array_filter($array, function ($value, $key) {
   return $value == 'Pratham' or $key == "Feedhive";
// Array ( [twitter] => Pratham [Feedhive] => Simon [CSS] => Pratham )


Now you know about array filter in PHP.

I recommend you to open a PHP files define arrays with different values and keys and try to filter those values and keys with array filter.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • array filter in php
  • modes in array filter
  • array filter arguments
  • filter array based on keys
  • filter arrays based on values
  • filter arrays based on key and values

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts