Reputation: 1784
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
Reputation: 316969
See
array_diff
— Computes the difference of arraysarray_intersect
— Computes the intersection of arraysExample:
$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
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
Reputation: 30595
Use preg_grep
:
$new_categories_array = preg_grep('/category_[23]/', $categories_array);
Upvotes: 0
Reputation: 9433
unset($new_categories_array[0]); unset($new_categories_array[3]);
..might do the trick
Upvotes: 3