How to remove an element from an array in PHP
Today, we will explain to you how to remove an element from an array in PHP. There are multiple ways to remove an element from an array in PHP but here we’ll show you the two ways with examples.
Similar articles
- Get keys from an associative array in PHP
- Remove keys from an associative array in PHP
- Multidimensional array search by value in PHP
- Insert an array into a MySQL database using PHP
Ways to remove an element from an Array
1. unset() function
In the below example, you can see how to use unset() function to remove the element from an array.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $myArray = array('Jacob', 'Denny', 'Aiden', 'Lincoln'); unset($myArray[1]); print_r($myArray); ?> // Output: Array ( [0] => Jacob [2] => Aiden [3] => Lincoln ) |
You can see in the above output array which is not reindexed after removing the element from an array. So we can use the array_values()
functions to get a re-indexed array.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $result = array_values($myArray); print_r($result); ?> // Output: Array ( [0] => Jacob [1] => Aiden [2] => Lincoln ) |
To remove key/values from the associative array, you can use unset() function as shown in the following example.
Example 2
Here, we have a student array and we will remove the branch key and its value from an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $student = array( 'name' => 'Denny', 'branch' => 'IT', 'marks' => 89 ); unset($student['branch']); pre($student); ?> // Output: Array ( [name] => Denny [marks] => 89 ) |
2. array_splice() function
In an alternative way, you can use array_splice() function to remove the specific element from an array.
Syntax
1 | array_splice($array, $start, $length, $newarray) |
Parameters
- $array (Required): Specifies an original array.
- $start (Required) : Specifies the offset where to start removing the element.
- $length (Optional): Specifies the number of elements to be removed. If this value is not set, the function will remove all the values starting from the $start parameter.
- $newarray (Optional): Specifies an array with elements which we want to insert into the original array.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $myArray = array('Jacob', 'Denny', 'Aiden', 'Lincoln'); array_splice($myArray,1,1); pre($myArray); ?> // Output: Array ( [0] => Jacob [1] => Aiden [2] => Lincoln ) |
Here, you can see the above output array is re-indexed.
That’s it for today.
Thank you for reading. Happy Coding..!!