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!

7
  • 1
    Define doesnt seem to work Commented Feb 14, 2013 at 13:07
  • 2
    unset is correct. How have you determined that it doesn't work? Commented Feb 14, 2013 at 13:07
  • Unset works but maybe your index is an int and the index you use for unsetting is a string? Commented Feb 14, 2013 at 13:09
  • I'll define doesnt seem to work: When you use unset, I have read that the array doesnt get "reindexed". Then I used array_values($array); , but im not sure about if thats working either. Commented Feb 14, 2013 at 13:09
  • 4
    See this stackoverflow.com/questions/5217721/… Commented Feb 14, 2013 at 13:18

4 Answers 4

1

unset should work, you can also try this:

$array = array_merge(
             array_slice($array, 0, $index),
             array_slice($array, $index+1)
         );
Sign up to request clarification or add additional context in comments.

1 Comment

slices array into 2 subarrays without the element that you want to remove and then merges them into one
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)

1 Comment

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]
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);

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.