Pennywise83
Pennywise83

Reputation: 1784

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'];

Upvotes: 2

Views: 241

Answers (4)

Gordon
Gordon

Reputation: 316969

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.

Upvotes: 2

Jamie Wong
Jamie Wong

Reputation: 18350

While I agree preg_grep is a good solution in your example, if you want a more general case function, look at array_filter - http://ca.php.net/manual/en/function.array-filter.php

Upvotes: 0

amphetamachine
amphetamachine

Reputation: 30595

Use preg_grep:

$new_categories_array = preg_grep('/category_[23]/', $categories_array);

Upvotes: 0

Matt
Matt

Reputation: 9433

unset($new_categories_array[0]);
unset($new_categories_array[3]);

..might do the trick

Upvotes: 3

Related Questions