8

I have an array like : [312, 401, 1599, 3]

With array_diff( [312, 401, 1599, 3], [401] ) I can remove a value, in my example I removed the value 401.

But if I have this : [312, 401, 401, 401, 1599, 3], how can remove just one time the value 401 ?

It is not important if I remove the first or last value, I just need to remove ONE 401 value, and if I want to remove all 401 values, I have to remove three times.

Thanks !

8
  • what is your current output?? I mean which one to remove? Commented Apr 9, 2016 at 13:55
  • my function remove all 401 values, si output is [312,1599,3] Commented Apr 9, 2016 at 13:55
  • but which one must remove?? Commented Apr 9, 2016 at 13:56
  • This seems like an odd requirement somehow. You don't want only one occurrence of 401 and you don't care about the index either. Just out of curiosity, what's the end goal here? Commented Apr 9, 2016 at 13:56
  • @FrayneKonok He apparently doesn't care: "It is not important if I remove the first or last value," Commented Apr 9, 2016 at 13:57

3 Answers 3

14

With array_search you can get the first matching key of the given value, then you can delete it with unset.

if (false !== $key = array_search(401, $array)) {
  unset($array[$key]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

With array_intersect you can retrieve all matching keys at once, which allows you to decide which specific one of them to remove with unset.

Comments

1

Search specific key and remove it:

if (($key = array_search(401, $array)) !== false) {
   unset($array[$key]); 
}

Man PHP:

array_search

unset

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.