Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a specific item by using array_splice/array_slice in PHP

Tags:

arrays

php

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

like image 797
lovespring Avatar asked Apr 12 '10 12:04

lovespring


People also ask

How can I remove a specific item from an array PHP?

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.

How do I remove a specific element from an array?

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.

What does array_splice () function do?

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


1 Answers

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!

like image 66
zhujy_8833 Avatar answered Oct 19 '22 22:10

zhujy_8833