PHP removes a specific element from an array in two ways
- 2020-07-21 07:15:10
- OfStack
Method 1:
<?php
$arr1 = array(1,3, 5,7,8);
$key = array_search(3, $arr1);
if ($key !== false)
array_splice($arr1, $key, 1);
var_dump($arr1);
?>
Output:
array(4) { [0]= > int(1) [1]= > int(5) [2]= > int(7) [3]= > int(8) }
Method 2:
<?php
$arr2 = array(1,3, 5,7,8);
foreach ($arr2 as $key=>$value)
{
if ($value === 3)
unset($arr2[$key]);
}
var_dump($arr2);
?>
Output:
array(4) { [0]= > int(1) [2]= > int(5) [3]= > int(7) [4]= > int(8) }
Summary: You can see the difference between using array_splice() to delete a particular value and using unset to delete a particular value.
When the array_splice() function is removed, the index value of the array changes.
With unset() removed, the index value of the array does not change.