WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Delete PHP Array Element by Value Not Key

Topic: PHP / MySQLPrev|Next

Answer: Use the array_search() Function

You can use the array_search() function to first search the given value inside the array and get its corresponding key, and later remove the element using that key with unset() function.

Please note that, if the value is found more than once, only the first matching key is returned.

Let's take a look at an example to understand how it actually works:

<?php
// Sample indexed array
$array1 = array(1, 2, 3, 4, 5);

// Search value and delete
if(($key = array_search(4, $array1)) !== false) {
    unset($array1[$key]);
}

print_r($array1);
echo "<br>";


// Sample eassociative array
$array2 = array("a" => "Apple", "b" => "Ball", "c" => "Cat");

// Search value and delete
if(($key = array_search("Cat", $array2)) !== false) {
    unset($array2[$key]);
}

print_r($array2);
?>

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties