How to delete an element from an array PHP.?
Deleting element from an array can be done in three ways.unset(),array_splice(),array_diff() methods can be used.
Delete one array element you can use
Also if you have the value and don't know the key to delete the element you can use
array_search() to get the key.
Lets take a look in each one of them.
The keys are not shuffled or renumbered. The
unset() key is simply removed and the others remain.
$a = array(1,2,3,4,5); unset($a); print_r($a); //Output Array (  => 1  => 2  => 4  => 5 )
array_splice — Remove a portion of the array and replace it with something else.
Removes the elements designated by
length from the
input array, and replaces them with the elements of the
replacement array, if supplied.
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); array_splice($a1,0,2); print_r($a1); //Output Array ( [c] => blue [d] => yellow )
The array_diff() function compares the values of two (or more) arrays, and returns the differences.
This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.
<?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_diff($a1,$a2); print_r($result); //Output Array ( [d] => yellow ) ?>