There are multiple ways to delete an element from an array in PHP. This article discusses some of the most common methods used in PHP to delete an element from an array.
Functions used:
- unset(): This function takes an element as a parameter and unset it. It wouldn’t change the keys of other elements.
- array_splice(): This function takes three parameters an array, offset (where to start), and length (number of elements to be removed). It will automatically re-index an indexed array but not an associated array after deleting the elements.
- array_diff(): This function takes an array and list of array values as input and deletes the giving values from an array. Like unset() method, it will not change the keys of other elements.
Steps used:
- Declare an associated array.
- Delete element from array.
- Print the result.
- Declare an indexed array.
- Delete an element from the indexed array.
- Print the result.
Example 1: This example uses unset() function to delete the element. The unset() function takes the array as a reference and does not return anything.
PHP
<?php
$ass_arr = [ "a" => "Geeks" , "b" => "For" , "c" => "Geeks" ];
unset( $ass_arr [ "b" ]);
print_r( $ass_arr );
$ind_arr = [ "Geeks" , "For" , "Geeks" ];
unset( $ind_arr [1]);
print_r( $ind_arr );
?>
|
Output
Array
(
[a] => Geeks
=> Geeks
)
Array
(
[0] => Geeks
[2] => Geeks
)
From the output we can see that unset() has not changed the index for other elements in indexed array.
Example 2: This example uses array_splice() function to delete element from array.
PHP
<?php
$ass_arr = [ "a" => "Geeks" , "b" => "For" , "c" => "Geeks" ];
array_splice ( $ass_arr ,1,1);
print_r( $ass_arr );
$ind_arr = [ "Geeks" , "For" , "Geeks" ];
array_splice ( $ind_arr ,1,1);
print_r( $ind_arr );
?>
|
Output
Array
(
[a] => Geeks
=> Geeks
)
Array
(
[0] => Geeks
[1] => Geeks
)
Example 3: This example uses array_diff() function to delete the elements. Please note that the array values are passed as second parameter not the index. This function takes array parameter by value not reference and returns an array as output.
PHP
<?php
$ass_arr = [ "a" => "Geeks" , "b" => "For" , "c" => "Geeks" ];
$ass_arr = array_diff ( $ass_arr ,[ "For" ]);
print_r( $ass_arr );
$ind_arr = [ "Geeks" , "For" , "Geeks" ];
$ind_arr = array_diff ( $ind_arr ,[ "For" ]);
print_r( $ind_arr );
?>
|
Output
Array
(
[a] => Geeks
=> Geeks
)
Array
(
[0] => Geeks
[2] => Geeks
)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Jul, 2021
Like Article
Save Article