0

I have done a lot of researching, and I cant find out how to delete an element from an array in PHP. In Java, if you have an ArrayList<SomeObject> list, you would say list.remove(someObject);.

Is there anything similar you can do in PHP? I have found unset($array[$index]);, but it doesnt seem to work.

Thanks for your help in advance!

ACetin
  • 97
  • 7

4 Answers4

1

unset($array[$index]); actually works.
The only issue I can think of is the way you're iterating this array.
just use foreach instead of for

also make sure that $index contains correct value

to test your array you can use var_dump():

$cars[0]="Volvo"; 
$cars[1]="BMW"; 
$cars[2]="Toyota"; 

unset($cars[0]);
var_dump($cars);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Lets say i have this array $cars[0]="Volvo"; $cars[1]="BMW"; $cars[2]="Toyota"; When i say unset($cars[0]), I only have [1] and [2] remaining, right? – ACetin Feb 14 '13 at 13:14
1

unset should work, you can also try this:

$array = array_merge(
             array_slice($array, 0, $index),
             array_slice($array, $index+1)
         );
asprin
  • 9,579
  • 12
  • 66
  • 119
pwolaq
  • 6,343
  • 19
  • 45
  • slices array into 2 subarrays without the element that you want to remove and then merges them into one – pwolaq Feb 14 '13 at 13:15
1

You need to either remove it and remove the empty array:

function remove_empty($ar){
    $aar = array();
    while(list($key, $val) = each($ar)){
        if (is_array($val)){
            $val = remove_empty($val);
            if (count($val)!=0){
                $aar[$key] = $val;
            }
        }
        else {
            if (trim($val) != ""){
                $aar[$key] = $val;
            }
        }
    }
    unset($ar);
    return $aar;
}

remove_empty(array(1,2,3, '', 5)) returns array(1,2,3,5)

Toping
  • 754
  • 5
  • 16
  • So if I have [1], [2], [3], [4], and i remove [2], i want the array to reindex the array, so instead of [1], [3], [4], i get [1], [2], [3] – ACetin Feb 14 '13 at 13:18
0

If you want to delete just one array element you can use unset() or alternative array_splice()

Unset()
Example :

Code

<?php

    $array = array(0 => "x", 1 => "y", 2 => "z");
    unset($array[1]);
    //If you want to delete the second index ie, array[1]
?>

Output

Array (
    [0] => a
    [2] => c
)
Jason
  • 661
  • 5
  • 17