Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using array_filter to remove array item based on sub property value

Within my WordPress environemnt, I have a PHP challenege I can’t wrap my brain around. I have an array called $tax_terms. I want to remove the item that has a sub property of name equal to ‘Staff’.

For a visual understanding, here is my array

$tax_terms

with echo '<pre>' . var_export($tax_terms, true) . '</pre>';, it prints the following to page…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array (
  2 => 
  WP_Term::__set_state(array(
     'term_id' => 400,
     'name' => 'Staff',
     'slug' => 'staff',
     'term_group' => 0,
     'term_taxonomy_id' => 400,
     'taxonomy' => 'business',
     'description' => '',
     'parent' => 0,
     'count' => 0,
     'filter' => 'raw',
     'term_order' => '0',
  )),
  3 => 
  WP_Term::__set_state(array(
     'term_id' => 362,
     'name' => 'Customers',
     'slug' => 'Customers',
     'term_group' => 0,
     'term_taxonomy_id' => 362,
     'taxonomy' => 'business',
     'description' => '',
     'parent' => 0,
     'count' => 1,
     'filter' => 'raw',
     'term_order' => '0',
  )),
 
  //...more array items...

)

The following works when I use array_filter() on it like so…

  $tax_terms = array_filter($tax_terms, function ($value) use ($tax_terms) {
    return $value != $tax_terms['2'];
  });

But I don’t want to do it that way. I want to know what I am removing based on the ‘name’ => ‘Staff’ value like so…

    $tax_terms = array_filter($tax_terms, function ($value) use ($tax_terms) {
      return $value != $tax_terms->name['Staff'];
    });

but that does not work and I don’t know why yet…Thanks for helping me learn how do this right.

>Solution :

Your $value function argument is an entire $tax_term item. You need to compare the property against the string Staff.

$tax_terms = array_filter($tax_terms, function($tax_term) use($tax_terms){
    return $tax_term->name != 'Staff';
});

Another way would be to iterate through the tax_terms array using foreach:

$filtered_tax_terms = [];

foreach($tax_terms as $tax_term){
    if( $tax_term->name != 'Staff' ){
        $filtered_tax_terms[] = $tax_term;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading