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 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net