Remove item from php array by passing value
I have a php array like this
Array
(
[0] => WVSE1P
[1] => WVSE1MA
[2] =开发者_Python百科> 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.
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);
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.
Unsetting array items while iterating over that array may cause some unexpected behaviour some times. Here's another solution:
$flipped = array_flip($array);
unset($flipped['WVSE1P']);
$array = array_flip($flipped);
This should work in this case. Just make sure, that all values are unique within the array.
精彩评论