phparraysfilteringarray-intersect

Remove multiple elements from a flat array using whitelisted values


I have an array like this:

$categories_array = ['category_1', 'category_2', 'category_3', 'category_4'];

I'd like to filter the array to get a new one. For example, I'd like to have a new array with only category_2 and category_3 and preserve the original keys like this:

$new_categories_array = [1 => 'category_2', 2 => 'category_3'];

Solution

  • See

    Example:

    $original = array('category_1','category_2','category_3','category_4');
    $new      = array_diff($original, array('category_1', 'category_4'));
    
    print_r($new);
    

    Output:

    Array
    (
        [1] => category_2
        [2] => category_3
    )
    

    When using array_intersect the returned array would contain cat 1 and 4 obviously.