Is it possible to remove a string (see example below) from a PHP array without knowing the index?

Example:

array = array("string1", "string2", "string3", "string4", "string5");

I need to remove string3.

share|improve this question

2 Answers

up vote 7 down vote accepted
$index = array_search('string3',$array);
if($index !== FALSE){
    unset($array[$index]);
}

if you think your value will be in their more than once try using array_keys with a search value to get all of the indexes. You'll probably want to make sure

share|improve this answer
I like this +1 for you. But, how can I confirm that it was removed (display on screen)? – Zachary Brown Nov 8 '10 at 1:38
Check out the php functions print_r and var_dump. You can use them to dump the contents of your array. – GWW Nov 8 '10 at 1:39

It sort of depends how big the array is likely to be, and there's multiple options.

If it's typically quite small, array_diff is likely the fastest consistent solution, as Jorge posted.

Another solution for slightly larger sets:

$data = array_flip($data);
unset($data[$item2remove]);
$data = array_flip($data);

But that's only good if you don't have duplicate items. Depending on your workload it might be advantageous to guarantee uniqueness of items too.

share|improve this answer

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.