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_filter(array,function,mode)

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

Modes

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

Examples

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';
});
print_r($filtered);
// 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_FILTER_USE_KEY);
print_r($filtered);
// 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_FILTER_USE_BOTH);
print_r($filtered);
// Array ( [twitter] => Pratham [Feedhive] => Simon [CSS] => Pratham )

Conclusion

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

Courses