0

I want to filter and delete an item from an array. is it possible to do it with array_filter() ?

//I want to delete these items from the $arr_codes
$id = 1223;
$pin = 35;

//Before
$arr_codes = Array('1598_9','1223_35','1245_3','1227_11', '1223_56');

//After
$arr_codes = Array('1598_9','1245_3','1227_11', '1223_56');

Thanks!

2
  • Is your criteria dynamic, or is it always $id = 1223 and $pin = 35? Commented May 25, 2011 at 2:05
  • Dynamic objects, this is just an example. Commented May 25, 2011 at 2:07

2 Answers 2

3

You can find the index of the value you are interested in with array_search and then unset it.

$i = array_search('1223_35',$arr_codes);
if($i !== false) unset($arr_codes[$i]);
Sign up to request clarification or add additional context in comments.

Comments

0

array_filter does not take userdata (parameters). array_walk() does. However, none of the iterator function allow modifying the array structure within the callback.

As such, array_filter() is the appropriate function to use. However, since your comparison data is dynamic (per your comment), you're going to need another way to obtain comparison data. This could be a function, global variable, or build a quick class and set a property.

Here is an example using a function.

array_filter($arr, "my_callback");

function my_callback($val) {
  return !in_array($val, get_dynamic_codes());
}

function get_dynamic_codes() {
  // returns an array of bad codes, i.e. array('1223_35', '1234_56', ...)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.