| Viewed 123 times

Deleting one element from an array in PHP


Deleting one element from an array in PHP

1 Answer
Mohammad Qandeel
Answered
10

There are a lot of ways to delete an element from an array according to your need.

unset() function used to destroy the specified variables 

we can use it to destroys array item like unset($array[2]);

Example 

<?php
    $array=[1,2,3,4];
    print_r($array);
    unset($array[2]);
    print_r($array);
?>

Output

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 

Array ( [0] => 1 [1] => 2 [3] => 4 )

as you see we initialize the array with 4 indexes from [0 to 3], after that we use the unset() function to destroy the array element that has index number 2 

if you want to indexes the array numerically use array_values() function 

Example 

<?php
    $array=[1,2,3,4];
    print_r($array);
    unset($array[2]);
    print_r($array);
    $array=array_values($array);
    print_r($array);
?>

Output

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 

Array ( [0] => 1 [1] => 2 [3] => 4 )

Array ( [0] => 1 [1] => 2 [2] => 4 )