Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: array_diff - remove one value

Tags:

arrays

php

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

like image 396
Maarten Hartman Avatar asked Jul 02 '26 03:07

Maarten Hartman


2 Answers

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]);
like image 98
nice ass Avatar answered Jul 04 '26 17:07

nice ass


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.

like image 22
Todd Kerpelman Avatar answered Jul 04 '26 17:07

Todd Kerpelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!