Tutorial :Filter an array



Question:

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?


Solution:1

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.


Solution:2

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

..might do the trick


Solution:3

Use preg_grep:

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


Solution:4

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »