Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Removing Array Elements

Another way of modifying arrays is to remove elements from them. To remove an element, you might try setting an array element to an empty string, "", like this:

<?php
    $fruits[0] = "pineapple";
    $fruits[1] = "pomegranate";
    $fruits[2] = "tangerine";

    $fruits[1] = "";

    for ($index = 0; $index < count($fruits); $index++){
        echo $fruits[$index], "\n";
    }
?>

But that doesn't remove the element; it only stores a blank in it:

pineapple

tangerine

To remove an element from an array, use the unset function:

unset($values[3]);

This actually removes the element $values[3]. Here's how that might work in our example:

<?php
    $fruits[0] = "pineapple";
    $fruits[1] = "pomegranate";
    $fruits[2] = "tangerine";

    unset($fruits[1]);

    for ($index = 0; $index < count($fruits); $index++){
        echo $fruits[$index], "\n";
    }
?>

Now when you try to display the element that's been unset, you'll get a warning:

pineapple
PHP Notice:  Undefined offset:  1 in C:\php\t.php on line 8
  • + Share This
  • 🔖 Save To Your Account