7

Straight to the point...

I have an array ($is_anonymous_ary) that looks like this:

array (
  [80] => 1
  [57] => 1
  [66] =>
  [60] => 
  [90] => 1
)

And another array ($user_id_ary) like this one:

array (
  [0] => 80
  [1] => 30
  [2] => 57
  [3] => 89
  [4] => 66
  [5] => 60
  [6] => 90
)

I need to unset values on the $user_id_ary based on the first array. So, if the value from $is_anonymous_ary is 1 (true), then take the key from that array, check against $user_id_ary, and unset the keys from $user_id_ary which had the value from the keys from $is_anonymous_ary.

I complicated the description a bit, here is how I need my final result:

user_id_ary = array(
  [0] => 30
  [1] => 89
  [2] => 66
  [3] => 60
)

As you see all keys from the $is_anonymous_ary that had a TRUE value, are gone in the second array. which had the keys from the first array as values in the second array.

Hope I made myself clear.

2
  • Can't this be done with a simple loop based intersect to remove based on === 1? Commented Oct 4, 2012 at 11:57
  • 1
    I don't know, hence this question. Commented Oct 4, 2012 at 11:57

4 Answers 4

6

Try array_filter:

$user_id_ary = array_filter($user_id_ary, function($var) use ($is_anonymous_ary) {
  return !(isset($is_anonymous_ary[$var]) && $is_anonymous_ary[$var] === 1);
});
Sign up to request clarification or add additional context in comments.

9 Comments

Why return? I am not working inside a function! Can you explain what your code does?
@Dugi Have you checked the manual? The element make the callback return false will be removed.
@Dugi The return decides whether to filter the array based on that condition or not. array_filter, without the function, will remove null values, with this function will remove based where the index isset and it === 1
Your answer worked after changing the identical comparison to ==. Thanks.
@Dugi That means it's string '1' not integer 1 in your array.
|
0
foreach($user_id_ary as $id){
   if($is_anonymous_ary[$id] == '1'){
      unset($d);
   }       
}

if this wont work, try to iterate thru each elem in user_id_array

Comments

0
$user_id_ary = array_diff($user_id_ary, array_keys(array_filter($is_anonymous_ary)));

Comments

0

How easy:)

$new_array =NULL;
foreach($is_anonymous_ary as $key=>$value){

  $new_array[] = array_search($key, $user_id_ary);
  unset($is_anonymous_ary[$key]);
}
$user_id_ary =  $new_array;

1 Comment

I need to keep working with $user_id_ary as the variable name, since it's used in more places than once. Any suggestion that doesn't get rid of my current $user_id_ary?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.