2

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.

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

If he does array_values() at the end, he's going to lose the keys in his array.
all it does is return the value sin the array and indexes them in order
Right, but what if he needs to keep the keys? It seems that $array = array_merge($array) would be better.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.