9

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 !

Clément Andraud
  • 9,103
  • 25
  • 80
  • 158
  • what is your current output?? I mean which one to remove? – Murad Hasan Apr 09 '16 at 13:55
  • my function remove all 401 values, si output is [312,1599,3] – Clément Andraud Apr 09 '16 at 13:55
  • but which one must remove?? – Murad Hasan Apr 09 '16 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? – jDo Apr 09 '16 at 13:56
  • @FrayneKonok He apparently doesn't care: *"It is not important if I remove the first or last value,"* – jDo Apr 09 '16 at 13:57
  • Why not just use a simple for each loop with a break statement when the first instance of the value is found. It seems silly to try to come up with some overly complex solution. – Pavlin Apr 09 '16 at 13:58
  • it was solve [here](http://stackoverflow.com/questions/16973365/keep-duplicates-while-using-array-diff) – MrFreezer Apr 09 '16 at 14:01
  • Well as from your array, I guess you already saw this question: http://stackoverflow.com/q/7225070/3933332 why don't you just use it? – Rizier123 Apr 09 '16 at 14:03

3 Answers3

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]);
}
Federkun
  • 36,084
  • 8
  • 78
  • 90
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.

Guido
  • 876
  • 5
  • 14
1

Search specific key and remove it:

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

Man PHP:

array_search

unset

Lifka
  • 249
  • 1
  • 7
  • 17