Removing elements from an array

suggest change

To remove an element inside an array, e.g. the element with the index 1.

$fruit = array("bananas", "apples", "peaches");
unset($fruit[1]);

This will remove the apples from the list, but notice that unset does not change the indexes of the remaining elements. So $fruit now contains the indexes 0 and 2.

For associative array you can remove like this:

$fruit = array('banana', 'one'=>'apple', 'peaches');

print_r($fruit);
/*
    Array
    (
        [0] => banana
        [one] => apple
        [1] => peaches
    )
*/

unset($fruit['one']);

Now $fruit is

print_r($fruit);

/*
Array
(
    [0] => banana
    [1] => peaches
)
*/

Note that

unset($fruit);

unsets the variable and thus removes the whole array, meaning none of its elements are accessible anymore.

Removing terminal elements

array_shift() - Shift an element off the beginning of array.

Example:

$fruit = array("bananas", "apples", "peaches");
array_shift($fruit);
print_r($fruit);

Output:

Array
(
   [0] => apples
   [1] => peaches
)

array_pop() - Pop the element off the end of array.

Example:

$fruit = array("bananas", "apples", "peaches");
array_pop($fruit);
print_r($fruit);

Output:

Array
(
   [0] => bananas
   [1] => apples
)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Manipulating an array:
* Removing elements from an array

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
88 Manipulating an array
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR