21

Possible Duplicate:
How to delete an element from an array in php?

I have a list of things, cars for instance

$cars[0] = "audi";
$cars[1] = "saab";
$cars[2] = "volvo";
$cars[3] = "vw";

How do i delete "volvo" from the list?

1

4 Answers 4

14
$volvoIndex = array_search('volvo', $cars);
unset($cars[$volvoIndex]);
Sign up to request clarification or add additional context in comments.

1 Comment

damn. you write faster than me! :P btw. +1 ;)
4

you can do with unset

unset($cars[2]);

But after that you need to iterate array with foreach

6 Comments

If you follow this up by doing $cars = array_filter($cars) it will remove the empty array items as well. :)
What happens if "volvo" is array item 3?
@Merjin What do you mean by "empty array item"?
Whoops. I meant 'empty strings' but I just tried and unset also removes the item from the array. No empty spaces left to trim, so ignore my other comment.
Thanks, @Gordon I used what rights I got right now.
|
3

You can use the following thing to delete the x element from array

array_splice($cars,2,1)

This will delete the 2nd element in array and return the remaining array, if you want more elemetns to be deleted change 1 to number of elements that needs to be deleted.

Comments

0

use this for example: unset($cars[2]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.