Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from php array by passing value

Tags:

arrays

php

I have a php array like this

Array
(
    [0] => WVSE1P
    [1] => WVSE1MA
    [2] => WVSEU1Y
    [3] => WVSEUP
)

how do i remove a particular entry in it by passing the value?

below is the code i tried:

$array = $items; //array is items

foreach($array as $key => $value) 
{

$val= 'WVSE1P'; //item to remove
if ($value == $val) unset($array[$key]);

}

but it doesn't seem to work.

like image 836
esafwan Avatar asked Dec 21 '25 23:12

esafwan


2 Answers

You should probably use array_splice instead of unset so that your array indexes match up correctly after unsetting.

How about this?:

$val = 'WVSE1P';
$items = array_splice($items, array_search($val), 1);
like image 86
Jordan Avatar answered Dec 24 '25 13:12

Jordan


This method removes any values in the specified array without any looping: Example:

$array = Array("blue", "orange", "red");

$array = array_diff($array, array("blue")); // blue will be removed

//optionally you can realign the elements:

$array = array_values($array);

The reason yours may not work is because you are containing it inside a loop which does not control the array object.

like image 27
1337XyPhR Avatar answered Dec 24 '25 12:12

1337XyPhR



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!