InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Deleting Elements from an Array in PHP
PHP

Deleting Elements from an Array in PHP

InfinityCoder November 19, 2016

You want to remove one or more elements from an array.

To delete one element, use unset():

1
2
unset($array[3]);
unset($array['foo']);

To delete multiple noncontiguous elements, also use unset():

1
2
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);

To delete multiple contiguous elements, use array_splice():

1
array_splice($array, $offset, $length);

Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:

1
$array[3] = $array['foo'] = '';

Besides syntax, there’s a logical difference between using unset() and assigning ” to the element. The first says, “This doesn’t exist anymore,” and the second says, “This still exists, but its value is the empty string.”
If you’re dealing with numbers, assigning 0 may be a better alternative. So if a company stopped production of the model XL1000 sprocket, it would update its inventory with:

1
unset($products['XL1000']);

However, if the company temporarily ran out of XL1000 sprockets but was planning to receive a new shipment from the plant later this week, this is better:

1
$products['XL1000'] = 0;

If you unset() an element, PHP adjusts the array so that looping still works correctly. It doesn’t compact the array to fill in the missing holes.

This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1];  // prints 'bee'
print $animals[2];  // prints 'cat'
count($animals);    // returns 6
 
// unset()
unset($animals[1]); // removes element $animals[1] = 'bee'
print $animals[1];  // prints nothing and throws an E_NOTICE error
print $animals[2];  // still prints 'cat'
count($animals);    // returns 5, even though $array[5] is 'fox'
 
// add new element
$animals[] = 'gnu'; // add new element (not Unix)
print $animals[1];  // prints nothing, still throws an E_NOTICE error
print $animals[6];  // prints 'gnu', this is where 'gnu' ended up
count($animals);    // returns 6
 
// assign ''
$animals[2] = '';  // zero out value
print $animals[2]; // prints ''
count($animals);   // returns 6, count does not decrease

To compact the array into a densely filled numeric array, use array_values():

1
$animals = array_values($animals);

Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:

1
2
3
4
5
6
7
8
9
10
11
12
// create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
 
Array
(
    [0] => ant
    [1] => bee
    [2] => elk
    [3] => fox
)

This is useful if you’re using the array as a queue and want to remove items from the queue while still allowing random access.

To safely remove the first or last element from an array, use array_shift() and array_pop(), respectively.

However, if you find yourself often running into problems because of holes in arrays, you may not be “thinking PHP.”

 

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Finding the Number of Rows Returned by a Query in PHP
You want to know how many rows a SELECT query …

Finding the Number of Rows Returned by a Query in PHP

Returning Failure in PHP
You want to indicate failure from a function. Return false: …

Returning Failure in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap