How to delete an element from an array PHP.?

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 unset() or array_splice().

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.

1.unset()

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[2]);
print_r($a);

//Output
Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
)

2.array_splice()

array_splice — Remove a portion of the array and replace it with something else.

Removes the elements designated by offset and 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 
)

3.array_diff()

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 )
?>

 

Categories: PHP Tags: #PHP 7,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.