Q:

How to Delete PHP Array Element by Value Not Key

0

How to Delete PHP Array Element by Value Not Key

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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);
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Push Both Key and Value Into an Array in PH... >>
<< How to Convert an Integer to a String in PHP...