tags:

views:

45

answers:

4

I have an array like this:

$categories_array = array(
[0] => 'category_1',
[1] => 'category_2',
[2] => 'category_3',
[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' like this:

$new_categories_array = array(
[1] => 'category_2',
[2] => 'category_3',
)

How can I accomplish this result?

+2  A: 
unset($new_categories_array[0]);
unset($new_categories_array[3]);

..might do the trick

Matt
mmm... that should work but I'd like to write a function where I can set the name of elements that I want to save, not to exclude.Something like this:my_function('category_2, category_3', $original_array);
Pennywise83
A: 

Use preg_grep:

$new_categories_array = preg_grep('/category_[23]/', $categories_array);
amphetamachine
that's total overkill
Gordon
+2  A: 

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.

Gordon
This is a good solution, but is it possible to tell the script the elements to "save" instead of the elements that will be removed?
Pennywise83
@Pennywise see update. you want `array_intersect` in that case.
Gordon
A: 

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

Jamie Wong