Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove specific item from array [duplicate]

Tags:

arrays

php

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 !

like image 718
Clément Andraud Avatar asked Apr 09 '16 13:04

Clément Andraud


People also ask

How do you remove duplicates from an array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

How do you remove duplicate values from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);

How do I remove duplicates in NG repeat?

You can use unique filter while using ng-repeat . If you use track by $index then unique won't work. ok, I used unique and its working now, thanks!


3 Answers

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]);
}
like image 70
Federkun Avatar answered Oct 25 '22 18:10

Federkun


Search specific key and remove it:

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

Man PHP:

array_search

unset

like image 27
Lifka Avatar answered Oct 25 '22 18:10

Lifka


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.

like image 31
Guido Avatar answered Oct 25 '22 18:10

Guido