PHP array delete an item

Say, you have an array like the following, how to delete “three”?

$arr = array("one", "two", "three", "four", "five");

PHP has this function called unset, with which you can do:


But… yea… there is no direct way to do something like array_delete_value(“three”)… I don’t understand why there is no easy way to do deletion by value…

You will need to get the array index first, whenever you want to delete by value. We will use array_search to get the index or key.

if ( ($key = array_search("three", $arr)) !== false) {

The above is better than traversing the whole array linearly.

If you need to do a global delete, use a while loop.

while ( ($key = array_search("three", $arr)) !== false) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s