Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

The code looks like this right now:

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

user items array: 501,501,502,502

results correctly in array: 502,502

Is it possible to remove only 1x501 instead of 2x501 value? or said differently: limit the removal by 1 value

array is then: 501,502,502

Any advice is appreciated

share|improve this question

2 Answers

up vote 2 down vote accepted

How about searching for the item, then removing it if it exists?

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

Using unset isn't quite as straightforward as you'd think. See Stefan Gehrig's answer in this similar question for details.

share|improve this answer
 
thanks this worked! –  Maarten Hartman Jan 30 at 23:42

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]);
share|improve this answer
 
And you can throw it in a loop: pastebin.com/xF2hhDnS –  Elliot B. Jan 30 at 23:18
 
The OP wanted to remove one value only. If he wants them all out, then array_diff would be a better choice –  onetrickpony Jan 30 at 23:20
 
That is what my code does. Take another look or try running it and output the results. –  Elliot B. Jan 30 at 23:56
 
Yes, I see now that you're iterating the needles. Still, only one replacement is needed in this case, so there's no point in using a loop –  onetrickpony Jan 30 at 23:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.