Deleting elements from an array in PHP (2024)

Deleting elements from an array in PHP (1)

Nadia S.

The ProblemJump To Solution

How do I remove elements from an array in PHP?

The Solution

The easiest way to delete an element from an array in PHP is by using unset().

Click to Copy

$fruits = ['apple', 'orange', 'pear'];unset($fruits[1]);

However, note that this does not re-index the array, so $fruits[2] will remain ‘pear’. We’ll go into more detail about that and explore some other options below.

Deleting a Single Element

To delete a single element from an array, you can use:

  • The array_splice() function, which removes the element based on its index and reindexes the array.
  • The unset() function, which removes the element by its key and removes the element’s index.

The array_splice() Function

The array_splice() function is the most versatile and direct solution for deleting an element from both indexed arrays and associative arrays (with key-value pairs).

We call the array_splice() function with three arguments:

  • the array,
  • the offset of the element to be removed, and
  • the number of elements you want to remove.

Given an indexed array, you can remove the element at index 0 and specify only one element to be removed:

Click to Copy

$fruits = ['apple', 'orange', 'pear'];// remove the first element and only remove one elementarray_splice($fruits, 0, 1);print_r($fruits);

This will output:

Click to Copy

Array( [0] => orange [1] => pear)

The array_splice() function is a convenient method to delete a single element from an associative array, as you can remove an element based on its offset rather than its key or value. For example:

Click to Copy

$codes = [ 'red' => 'apple', 'orange' => 'orange', 'blue' => 'blueberry'];array_splice($codes, 0, 1);print_r($codes);

Output:

Click to Copy

Array( [orange] => orange [blue] => blueberry)

The unset() Function

Use unset() to remove an element by its key.

Click to Copy

$fruits = ['apple', 'orange', 'pear'];// remove the second elementunset($fruits[1]);print_r($fruits);

The output is:

Click to Copy

Array( [0] => apple [2] => pear)

Removing an element from an array using the unset() function results in the element’s index being removed too. If the consecutive numerical indexing of your array is important, you can follow the unset() function with the array_values() function. The array_values() function doesn’t update the array but returns a new array, so we need to create a variable to store the value of array_values().

Here we reindex the array with array_values() so that pear is at index one:

Click to Copy

// array_values() - converts keys to numerical values$reset = array_values($fruits);print_r($reset);

The output is:

Click to Copy

Array( [0] => apple [1] => pear)

Note that using the array_values() function with an associative array will return a new array with numeric keys, for example:

Click to Copy

$colors = [ 'red' => 'apple', 'orange' => 'orange', 'blue' => 'blueberry'];$colorsTest = array_values($colors);print_r($colorsTest);

The output is:

Click to Copy

Array( [0] => apple [1] => orange [2] => blueberry)

If you want to delete an element from an array but you only know its value, you can use array_search() to find the key of the element, and then use unset() to remove the key-value pair. Note that if there are duplicate elements in the array, array_search() will only return the first match.

Click to Copy

$colors = [ 'red' => 'apple', 'orange' => 'orange', 'blue' => 'blueberry'];$findKey = array_search('apple', $colors);print_r($findKey);

The output is:

Click to Copy

red

Now we use unset() to remove the key-value pair from the array:

Click to Copy

unset($colors['red']);print_r($colors);

Output:

Click to Copy

Array( [orange] => orange [blue] => blueberry)

Deleting Multiple Elements

To delete multiple nonconsecutive elements from an array, you can use:

  • The array_diff() function, which deletes elements and their indices from an indexed or associative array with the values as input.
  • The array_diff_key() function, which removes elements from an associative array using their keys as arguments.

The array_diff() Function

In this example, we call array_diff() on an indexed array to create a new array without John, Sue, and Sean:

Click to Copy

$names = ['John', 'Mary', 'Sue', 'Daniel', 'Sean'];$newNames = array_diff($names, ['John', 'Sue', 'Sean']);print_r($newNames);

The output contains the remaining elements but the indexes are no longer sequential:

Click to Copy

Array( [1] => Mary [3] => Daniel)

As with unset(), you can use array_values() to reindex the output:

Click to Copy

Array( [0] => Mary [1] => Daniel)

We can use array_diff() on an associative array to create a new array with elements removed based on their values. This is handy in cases where you aren’t sure of the keys of the elements to be removed.

Click to Copy

$jobs = [ 'Lawyer' => 'John', 'Teacher' => 'Mary', 'Chef' => 'Sue', 'Driver' => 'Daniel', 'Doctor' => 'Sean'];$newJobs = array_diff($jobs, ['John', 'Sue', 'Sean']);print_r($newJobs);

Output:

Click to Copy

Array( [Teacher] => Mary [Driver] => Daniel)

The array_diff_key() Function

Use the array_diff_key() function when you want to delete several elements from an array using their key values.

Click to Copy

$times = [ '8:00' => 'morning', '12:00' => 'noon', '19:00' => 'night'];// the values can be set to an empty string, or any character or string$newTimes = array_diff_key($times, ['8:00' => '', '12:00' => '']);print_r($newTimes);

Output:

Click to Copy

Array( [19:00] => night)

Deleting elements from an array in PHP (2024)

FAQs

How to delete elements in array PHP? ›

The easiest way to delete an element from an array in PHP is by using unset() . $fruits = ['apple', 'orange', 'pear']; unset($fruits[1]); However, note that this does not re-index the array, so $fruits[2] will remain 'pear'.

How do I delete elements in an array? ›

You can remove an item from an array in Javascript using the splice() method. splice() takes two parameters, the starting index and number of items to be removed from the array. var arr = ["apple", "orange", "banana"]; arr. splice(1,1);

How do you clean up an array in PHP? ›

PHP Delete Array Items

To remove an existing item from an array, you can use the array_splice() function. With the array_splice() function you specify the index (where to start) and how many items you want to delete.

How to delete from array by value in PHP? ›

To delete array elements by value using array_values() with array_splice() in PHP, find the key of the value, splice the array at that key, then reindex the array using array_values().

How to delete all data in an array in PHP? ›

We use the unset() function, which we use to destroy variables to subtract or destroy one of the arrays you create. In fact, you can use this function to destroy all variable types. <? php $fruits[0] = 'Apple'; $fruits[1] = 'Pear'; // just to delete an array: unset ($fruits[0]); // to delete all: unset ($fruits); ?>

How to remove empty elements from array in PHP? ›

You can use the PHP array_filter() function remove empty array elements or values from an array in PHP. This will also remove blank, null, false, 0 (zero) values.

How to make PHP array empty? ›

Syntax to create an empty array:

In other words, the initialization of new array is faster, use syntax var first = [] rather while using syntax var first = new Array(). The fact is being a constructor function the function Array() and the, [] is a part of the literal grammar of array.

How to remove the last data from an array in PHP? ›

In PHP, you can remove the last element from an array by reversing the array with array_reverse(), using array_shift() to remove the first element (previously the last), and then reversing the array back to its original order.

How to remove values from simple array in PHP? ›

  1. The unset() function removes a specified element from an array. ...
  2. The array_splice() function removes elements from an array by specifying the start index and the number of elements to delete. ...
  3. The array_diff() function removes specified values from an array by comparing array elements with given values.
Jul 9, 2024

How to remove common value from array in PHP? ›

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

What are some efficiency considerations for array insertion and deletion? ›

If the array has space available, inserting an element at the end takes constant time. Deleting an element from the beginning or middle of the array requires shifting the remaining elements, resulting in a linear time complexity. Deleting the last element of an array can be done in constant time.

How to remove unique elements from array in PHP? ›

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.

How to remove space from array element in PHP? ›

Using str_split() and array_filter() Method

The str_split() function splits the string into an array of single characters. The array_filter() function is then used to remove the spaces from this array. Finally, implode() is used to join the remaining characters back into a string without spaces.

What is array_splice in PHP? ›

The array_splice() method takes an array as its input value and replaces elements within the array with new elements. The developer can specify within the method the starting index value for the replacement values, and the length of the values to be replaced.

What is array_flip in PHP? ›

The array_flip() method is used to interchange the keys and values of an array. It creates a new array where the original array's values become the keys, and the keys become the values. This function can be useful in situations where it's needed to quickly lookup keys based on their previous values.

Top Articles
U.S.: reported to infidelity 2021 | Statista
Take the mystery out of CalSTRS and CalPERS retirement benefits
Joe Taylor, K1JT – “WSJT-X FT8 and Beyond”
Cappacuolo Pronunciation
Rubratings Tampa
Thor Majestic 23A Floor Plan
Cash4Life Maryland Winning Numbers
Free Atm For Emerald Card Near Me
Coffman Memorial Union | U of M Bookstores
Crossed Eyes (Strabismus): Symptoms, Causes, and Diagnosis
Directions To 401 East Chestnut Street Louisville Kentucky
Celsius Energy Drink Wo Kaufen
Globe Position Fault Litter Robot
How Quickly Do I Lose My Bike Fitness?
Aces Fmc Charting
Blog:Vyond-styled rants -- List of nicknames (blog edition) (TouhouWonder version)
Google Feud Unblocked 6969
Pekin Soccer Tournament
R Personalfinance
Water Trends Inferno Pool Cleaner
Rochester Ny Missed Connections
Red8 Data Entry Job
The Many Faces of the Craigslist Killer
Ecampus Scps Login
Regina Perrow
EVO Entertainment | Cinema. Bowling. Games.
Angel Haynes Dropbox
Mjc Financial Aid Phone Number
Bridgestone Tire Dealer Near Me
Publix Daily Soup Menu
Acuity Eye Group - La Quinta Photos
140000 Kilometers To Miles
Babbychula
Kvoa Tv Schedule
42 Manufacturing jobs in Grayling
Admissions - New York Conservatory for Dramatic Arts
Orion Nebula: Facts about Earth’s nearest stellar nursery
PruittHealth hiring Certified Nursing Assistant - Third Shift in Augusta, GA | LinkedIn
Vocabulary Workshop Level B Unit 13 Choosing The Right Word
Bob And Jeff's Monticello Fl
Trivago Sf
Collision Masters Fairbanks
Kenwood M-918DAB-H Heim-Audio-Mikrosystem DAB, DAB+, FM 10 W Bluetooth von expert Technomarkt
Sam's Club Gas Price Sioux City
Advance Auto.parts Near Me
antelope valley for sale "lancaster ca" - craigslist
18 Seriously Good Camping Meals (healthy, easy, minimal prep! )
Heat Wave and Summer Temperature Data for Oklahoma City, Oklahoma
View From My Seat Madison Square Garden
Prologistix Ein Number
Dr Seuss Star Bellied Sneetches Pdf
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 5990

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.