How do I delete a specific item by using array_splice
/array_slice
in PHP?
for example: array('a','b','c'); how to just delete 'b'? so the array remains: array('a','c');
Thanks
In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).
Actually. I came up with two ways to do that. It depends on how you are going to handle with the index issue.
If you want to remain the indices after deleting certain elements from an array, you would need unset().
<?php
$array = array("Tom","Jack","Rick","Alex"); //the original array
/*Here, I am gonna delete "Rick" only but remain the indices for the rest */
unset($array[2]);
print_r($array);
?>
The out put would be:
Array ( [0] => Tom [1] => Jack [3] => Alex ) //The indices do not change!
However, if you need a new array without keeping the previous indices, then use array_splice():
<?php
$array = array("Tom","Jack","Rick","Alex"); //the original array
/*Here,we delete "Rick" but change indices at the same time*/
array_splice($array,2,1); // use array_splice()
print_r($array);
?>
The output this time would be:
Array ( [0] => Tom [1] => Jack [2] => Alex )
Hope, this would help!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With