Filter Array Element in PHP

Introduction

This article explains the Filters Array Element in PHP. For this explanation I will use some functions like the Array_filter() function. This function filters the elements or values of an array using a callback function. The array_filter() function passes each value of the input array to the callback function. If the callback function returns true then something. The array filter function is very useful for removing empty elements in an array. You will see that phenomenon in the example below.

Syntax

This function filters elements of an array using a callback function. The syntax is:

Array_filter($array ,callback function);

 

Parameter Description
Array Required: Use a specific array for filtering
Callback Required: A specific callback function to be used

This function returns the filter array element.

Let's start with the first example. I will find an even and odd number using the callback array_filter() function. Such as in the following:

Example

<?php

function odd($element)

{

    return($element & 1);

}

function even($element)

{

    return(!($element & 1));

}

$data1 = array(

               "a"=>5,

               "b"=>9,

               "c"=>7,

               "d"=>4,

               "e"=>12

              );

$data2 = array(61, 72, 83, 34, 55, 44, 20);

echo "Odd Number:";

echo "<pre>";

print_r(array_filter($data1, "odd"));

echo "<br>";

echo "<b>Even Number:</b>";

echo "<pre>";

print_r(array_filter($data2, "even"));

?>

Output

array filter1.jpg

I will next use the array_filter() function in the next example without a callback function. You will see that in the following.

Example

<?php

$entry = array(

             0 => 'foo',

             1 => false,

             2 => -1,

             3 => true,

             4 => '',

             5 => 'hello',

             6 => 'MCN',

             7 => '',

             8 => 123,

             9 => null,

             10 => 'good'

          );

echo "<pre>";

print_r(array_filter($entry));

?>

Output

array filter2.jpg

I show in this example removal of empty elements or values in an array and count the values. This example describes the use of array_filter() using a callback function.

Example

<?php

function value($element)

{

if($element==null)

{

    unset($element);

}

else

{

return($element);

}

}

$data1 = array(

              "a"=>5,

              "b"=>9,

              "c"=>true,

              "d"=>4,

              "e"=>false,

              "f"=>''

              );

$data=array_filter($data1, "value");

echo "<pre>";

print_r($data)."<br>";

echo  'value is: '.count($data);

?>

Output

 array filter3.jpg


Similar Articles