Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter an array by a condition

I have an array like this:

array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2) 

Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.

So my expected result array would be:

array("a" => 2, "c" => 2, "f" => 2) 

Note: I want to keep the keys from the original array.

How can I do that with PHP? Any built-in functions?

like image 801
menardmam Avatar asked Oct 01 '09 12:10

menardmam


People also ask

How do you filter data from an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you add multiple conditions to a filter?

If you want to put multiple conditions in filter , you can use && and || operator.

Can we write if condition in filter?

To answer the question in the title: you can use if inside filter . filter accepts a function; in a classical function(arg) { ... } function, you can use if , obviously.

Which function filter the values of an array?

The JavaScript filter array function is used to filter an array based on specified criteria. After filtering it returns an array with the values that pass the filter. The JavaScript filter function iterates over the existing values in an array and returns the values that pass.


2 Answers

$fullArray = array('a'=>2,'b'=>4,'c'=>2,'d'=>5,'e'=>6,'f'=>2);   function filterArray($value){     return ($value == 2); }  $filteredArray = array_filter($fullArray, 'filterArray');  foreach($filteredArray as $k => $v){     echo "$k = $v"; } 
like image 148
Simon Avatar answered Oct 02 '22 19:10

Simon


You somehow have to loop through your array and filter each element by your condition. This can be done with various methods.

Loops while / for / foreach method

Loop through your array with any loop you want, may it be while, for or foreach. Then simply check for your condition and either unset() the elements if they don't meet your condition or write the elements, which meet the condition, into a new array.

Looping

//while loop while(list($key, $value) = each($array)){     //condition }  //for loop $keys = array_keys($array); for($counter = 0, $length = count($array); $counter < $length; $counter++){     $key = $keys[$counter];     $value = $array[$key];     //condition  }  //foreach loop foreach($array as $key => $value){     //condition } 

Condition

Just place your condition into the loop where the comment //condition is. The condition can just check for whatever you want and then you can either unset() the elements which don't meet your condition, and reindex the array with array_values() if you want, or write the elements in a new array which meet the condition.

//Pseudo code //Use one of the two ways if(condition){  //1. Condition fulfilled     $newArray[ ] = $value;             //↑ Put '$key' there, if you want to keep the original keys             //Result array is: $newArray  } else {        //2. Condition NOT fulfilled     unset($array[$key]);     //Use array_values() after the loop if you want to reindex the array     //Result array is: $array }  

array_filter() method

Another method is to use the array_filter() built-in function. It generally works pretty much the same as the method with a simple loop.

You just need to return TRUE if you want to keep the element in the array and FALSE if you want to drop the element out of the result array.

//Anonymous function $newArray = array_filter($array, function($value, $key){     //condition }, ARRAY_FILTER_USE_BOTH);  //Function name passed as string function filter($value, $key){     //condition } $newArray = array_filter($array, "filter", ARRAY_FILTER_USE_BOTH);  //'create_function()', NOT recommended $newArray = array_filter($array, create_function('$value, $key', '/* condition */'), ARRAY_FILTER_USE_BOTH); 

preg_grep() method

preg_grep() is similar to array_filter() just that it only uses regular expression to filter the array. So you might not be able to do everything with it, since you can only use a regular expression as filter and you can only filter by values or with some more code by keys.

Also note that you can pass the flag PREG_GREP_INVERT as third parameter to invert the results.

//Filter by values $newArray = preg_grep("/regex/", $array); 

Common conditions

There are many common conditions used to filter an array of which all can be applied to the value and or key of the array. I will just list a few of them here:

//Odd values return $value & 1;  //Even values return !($value & 1);  //NOT null values return !is_null($value);  //NOT 0 values return $value !== 0;  //Contain certain value values return strpos($value, $needle) !== FALSE;  //Use 'use($needle)' to get the var into scope  //Contain certain substring at position values return substr($value, $position, $length) === $subString;  //NOT 'empty'(link) values array_filter($array);  //Leave out the callback parameter 
like image 44
Gumbo Avatar answered Oct 02 '22 20:10

Gumbo