PHP array_filter() Function with Example

PHP array_filter() Function: Here, we will find out about the array_filter() work with example in PHP.

PHP array_filter() Function

array_filter() work is utilized to apply a channel on cluster components dependent on the capacity and returns the exhibit with separated components, it acknowledges an exhibit to be checked and a callback work. The callback work is utilized to approve the components in the cluster.

Syntax:

array_filter(array,callback_function) : array

Here,

  • the exhibit is the info cluster in which we need to apply the channel.
  • callback_function is the capacity, wherein we compose the condition to be approved.

Example:

    Input:
    $arr = array(10, 20, -10, -20, 50, 0);

    //here we have to filter the positive numbers 
    //the callback function to check the positive number is "isPositive()"
    Function calling: 
    $temp = array_filter($arr, "isPositive");

    Output:
    Array
    (
        [0] => 10
        [1] => 20
        [4] => 50
    )

    So, here 0th , 1st and 4th elements are positive

PHP code 1: Find the positive number from a given cluster of the numbers.

<?php
    //function to check wheather number is positive or not
    function isPositive($val)
    {
        if($val>0)
            return $val;
    }
    
    // array 
    $arr = array(10, 20, -10, -20, 50, 0);
    
    // array with only positive value
    $temp = array_filter($arr, "isPositive");
    
    print_r ($temp);
    
?>

Output:

Array
(
    [0] => 10
    [1] => 20
    [4] => 50
)

PHP code 2: Find the people who are qualified for casting a ballot from a given exhibit of people

Here, we likewise have the “keys” and dependent on the age key we are checking the democratic qualification.

<?php
    //function to check wheather person is eligible
    //for voting or not?
    function isVoter($val)
    {
        if($val['age']>=18)
            return $val;
    }
    
    // person's array 
    $arr = array(
            array("name" => "Kishan", "age" => 24,"city" => "Bilaspur",),
            array("name" => "Durgesh", "age" => 27,"city" => "Raipur",),
            array("name" => "Aakash", "age" => 44,"city" => "Delhi",),
            array("name" => "Prakash", "age" => 17,"city" => "Goa",),
        );
    
    // array with voting eligible persons
    $temp = array_filter($arr, "isVoter");
    
    print_r ($temp);
    
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Kishan
            [age] => 24  
            [city] => Bilaspur
        )
         
    [1] => Array          
        (
            [name] => Durgesh
            [age] => 27   
            [city] => Raipur
        )
         
    [2] => Array          
        (
            [name] => Aakash
            [age] => 44   
            [city] => Delhi
        )
         
)

Leave a Comment

error: Alert: Content is protected!!