Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from an array where they match a certain criteria in PHP

I have an array of products and i need to remove all of them which have a reference to webinar

The PHP version I am using is 5.2.9

$category->products

example:

    [6] => stdClass Object
            (
                [pageName] => another_title_webinar
                [title] => Another Webinar Title
            )

        [7] => stdClass Object
            (
                [pageName] => support_webinar
                [title] => Support Webinar
            )
[8] => stdClass Object
            (
                [pageName] => support
                [title] => Support
            )

In this case number 8 would be left but the other two would be stripped...

Could anyone help?

like image 210
Andy Avatar asked Dec 17 '12 10:12

Andy


People also ask

How do I remove a specific element from an array in PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.

How do you remove matching values from an array?

1) Remove duplicates from an array using a Set To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


3 Answers

Check out array_filter(). Assuming you run PHP 5.3+, this would do the trick:

$this->categories = array_filter($this->categories, function ($obj) {
    if (stripos($obj->title, 'webinar') !== false) {
        return false;
    }

    return true;
});

For PHP 5.2:

function filterCategories($obj)
{
    if (stripos($obj->title, 'webinar') !== false) {
        return false;
    }

    return true;
}

$this->categories = array_filter($this->categories, 'filterCategories');
like image 140
smottt Avatar answered Sep 23 '22 09:09

smottt


You can try

$category->products = array_filter($category->products, function ($v) {
    return stripos($v->title, "webinar") === false;
});

Simple Online Demo

like image 38
Baba Avatar answered Sep 23 '22 09:09

Baba


You could use the array_filter method. http://php.net/manual/en/function.array-filter.php

function stripWebinar($el) {
  return (substr_count($el->title, 'Webinar')!=0);
}

array_filter($category->products, "stripWebinar")
like image 31
Hugo Delsing Avatar answered Sep 23 '22 09:09

Hugo Delsing