Search code examples
phparraysarray-filter

php array_filter returns empty array on array of objects


i want to filter list of objects with small callback, got this weird behavior on this small piece of code:

var_dump($product_categories[90]->slug);
var_dump($last_part);
var_dump($last_part==$product_categories[90]->slug);
$req_obj = array_filter($product_categories, 
                        function($a)
                            {
                                if ((string)$a->slug == $last_part) return true;
                            });
var_dump($req_obj);

it gives output like this, cant figure out why is the final array $req_obj is empty ? :/

string 'bobby' (length=5)
string 'bobby' (length=5)
boolean true
array (size=0)
  empty

var_dump of $product_categories:

array (size=177)
  0 => 
    object(stdClass)[5988]
      public 'term_id' => string '38' (length=2)
      public 'name' => string 'bobby' (length=22)
      public 'slug' => string 'bobby' (length=12)
      public 'term_group' => string '0' (length=1)
      public 'term_taxonomy_id' => string '1369' (length=4)
      public 'taxonomy' => string 'product_cat' (length=11)
      public 'description' => string '...'
      public 'parent' => string '0' (length=1)
      public 'count' => int 591
      public 'meta_id' => string '1519' (length=4)
      public 'woocommerce_term_id' => string '38' (length=2)
      public 'meta_key' => string 'order' (length=5)
      public 'meta_value' => string '1' (length=1)
  1 => 
    object(stdClass)[5983]
    ...

Solution

  • $last_part is out of scope:

    function($v) use($last_part){
        return $v->slug == $last_part;
    }