greener
greener

Reputation: 5069

PHP Array: array filter with argument

I have this simple array in PHP that I need to filter based on an array of tags matching those in the array.

Array
(
    [0] => stdClass Object
        (
            [name] => Introduction
            [id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
            [tags] => Array
                (
                    [0] => client corp
                    [1] => version 2
                )
        )

    [1] => stdClass Object
        (
            [name] => Chapter one
            [id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
            [tags] => Array
                (
                    [0] => pro feature
                )
        )
)

When supplied with 'client corp', the output should be the above array with only the first item.

So far I have this:

$selectedTree = array_filter($tree,"checkForTags");

function checkForTags($var){

   $arr = $var->tags;
   $test = in_array("client corp", $arr, true);

   return ($test);
}

However, the result is that it's not filtering. When I echo $test, I get 1 all the time. What am I doing wrong?

Upvotes: 0

Views: 103

Answers (2)

RichardBernards
RichardBernards

Reputation: 3097

Something like this should do the trick:

$selectedTree = array_filter(array_map("checkForTags", $tree ,array_fill(0, count($tree), 'client corp')));

function checkForTags($var, $exclude){
   $arr = $var->tags;
   $test = in_array($exclude, $arr, true);
   return ($test ? $var : false);
}

array_map() makes sure you can pass arguments to the array. It returns each value altered. So in the returning array, some values are present, others are set to false. array_filter() with no callback filters all falsey values from that array and you are left with the desired result

Upvotes: 1

N.DeNisse
N.DeNisse

Reputation: 149

The in_array() function returns TRUE if needle is found in the array and FALSE otherwise. So by getting 1 as a result that means that "client corp" is found.

Check PHP in_array() manual

You can user array_search() to return the array key instead of using in_array().

Upvotes: 0

Related Questions