PHP: array_diff - delete one value

I am currently trying to use array_diff to remove 1 value from an array.

The code looks like this:

$item_id = 501;
$array = array_diff($user_items, array($item_id));

      

array of custom elements: 501 501 502 502

correctly displayed in the array: 502,502

Is it possible to remove only 1x501 instead of the 2x501 value? or else: limit the deletion to 1 value

array: 501 502 502

Any advice is appreciated

+3


source to share


2 answers


How about finding an element and then removing it if it exists?

$key = array_search($item_id, $user_items)
if ($key !== FALSE) {
  unset($user_items[$key]);
}

      



The usage is unset

not as straightforward as you might think. See Stefan Gehrig's article on this similar question for more details .

+2


source


You can use array_search

to find and remove the first value:



$pos = array_search($item_id, $user_items);

if($pos !== false)
  unset($user_items[$pos]);

      

+5


source







All Articles