tags:

views:

192

answers:

7
+1  Q: 

php array filter

I have and array (from json feed)... that array contain a lot of value, i only need some, so filter is the option...

let say the array contain (a=2,b=4,c=2,d=5,e=6,f=2)

I like to check all the value that is = 2, and DELETE the value that is not = 2

the resulting array will be (a=2, c=2, f=2)

so a foreach or while will print ONLY the value left, 3 of them !

question : how to do this in php ?

Thanks in advance

+8  A: 
$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";
}
Simon
that ask to make a different function for each request... is it possible to ass an extra var ? (2 as variable)
marc-andre menard
A: 

You would pass a filter function to array_filter. Either the name of a regular function:

function is_two($val) {
    return $val == 2;
}
$filtered = array_filter($arr, 'is_two');

Or the name of a just created anonymous function:

$filtered = array_filter($arr, create_function('$val', 'return $val == 2;'));

Since PHP 5.3 you can also use the lambda function syntax:

$filtered = array_filter($arr, function($val) { return $val == 2; });
Gumbo
It doesn't pass $arr by reference, and instead returns a new array which you're not capturing.
Simon
Gumbo
+1  A: 

You can iterate on the copies of the keys to be able to use unset() in the loop:

foreach (array_keys($array) as $key) {
    if ($array[$key] != 2)  {
        unset($array[$key]);
    }
}

The advantage of this method is memory efficiency if your array contains big values - they are not duplicated.

EDIT I just noticed, that you actually only need the keys that have a value of 2 (you already know the value):

$keys = array();
foreach ($array as $key => $value) {
    if ($value == 2)  {
        $keys[] = $key;
    }
}
soulmerge
A: 

I might do something like:

$newarray = array();
foreach ($jsonarray as $testelement){
    if ($testelement == 2){$newarray[]=$testelement}
}
$result = count($newarray);
Alex Mcp
A: 

Check out the example on the array_filter page.

outis
A: 
  foreach ($aray as $key => $value) {
    if (2 != $value) {
      unset($array($key));
    }
  }

  echo 'Items in array:' . count($array);
Goran Jurić
+1  A: 

This should work, but I'm not sure how efficient it is as you probably end up copying a lot of data.

$newArray = array_intersect_key(
                  $fullarray, 
                  array_flip(array_keys($fullarray, 2))
            );
Tom Haigh