How to use array_search() and unset() Functions In PHP
You can combine array_search() to find the index of the value and unset() to remove it.
Example: The array_search() function finds the index of the value to be removed, and unset() removes the element at that index.
<?php
$arr = array(1, 2, 3, 4, 5);
// Find the index of the value 3
$key = array_search(3, $arr);
if ($key !== false) {
// Remove the element at
// the given index (key)
unset($arr[$key]);
}
print_r($arr);
?>
Output
Array ( [0] => 1 [1] => 2 [3] => 4 [4] => 5 )
Different Ways to Delete an Item From an Array in PHP
Given an array containing some elements, the task is to Delete an item from an array using PHP.
Below are the approaches to delete an item from an Array in PHP:
Table of Content
- Using unset() Function
- Using array_splice() Function
- Using array_diff() Function
- Using array_filter() Function
- Using array_search() and unset() Functions
- Using a Loop to Remove Multiple Occurrences