Deleting a specific item by using array_splice/array_slice in PHP

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!


Basically: Just do it.

The manual has good examples like this one:

$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

if something doesn't work out for you, please add more detail to your question.


how to just delete "blue"?

Here you go:

$input = array("red", "green", "blue", "yellow");
array_splice($input, array_search('blue', $input), 1);

Tags:

Php

Arrays