Remove key and value from an associative array in PHP (2024)

May 9, 2022 ‐3min read

To remove a key and its respective value from an associative array in PHP you can use the unset() function.

&LT?php$mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go'];unset($mascots['Gopher']);print_r($mascots);// Array// (// [ElePHPant] => php// [Geeko] => openSUSE// )

As the name of the function suggests, you use the unset() function to unset a given variable or in this case an array key with its value.

Remove multiple keys from associative array

Removing multiple keys from associative array can be done using the unset() as well. You can pass as many keys to unset as arguments to the unset() function. See the example below where two keys are dropped from the associative array.

&LT?php$mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go'];unset($mascots['Gopher'], $mascots['Geeko']);print_r($mascots);// Array// (// [ElePHPant] => php// )

However useful, the approach above might get somewhat tedious when you need to remove multiple keys from the associative array. In that case there is another option, the array_diff() function. The array_diff() function compares the array you pass it as its first argument and returns an array with the values not present in the array you pass it in the second array.

In contrast to the other options I present here this approach require you to specify the values for which you remove the keys (and values). Instead of keys for which you wish to remove the values (and keys).

&LT?php$mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go'];$values = array_diff($mascots, ['openSUSE', 'Go']);print_r($values);// Array// (// [ElePHPant] => php// )

This last approach seems especially convenient if you need to remove the keys (and values) dynamically in your code.

Remove all keys from associative array

To remove all keys from an associative PHP array is to basically turn the array into a regular numerically indexed array. This can be achieved by grabbing just the values from the associative PHP array.

Since associative arrays in PHP are ordered, just like numerically indexed arrays, we can grab just the values and maintain the original order of the array.

&LT?php$mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go'];$values = array_values($mascots);print_r($values);// Array// (// [0] => php// [1] => openSUSE// [2] => Go// )

The above code sample creates a new array from the values of $mascots and stores the result in the variable $values. The $values array is a regular numerically indexed array, thus all the keys from the associative array $mascots are not present anymore.

As an expert in PHP programming, particularly in array manipulation and handling, I can confidently delve into the concepts and functions mentioned in the provided article regarding associative arrays in PHP.

The article discusses several methods to manipulate associative arrays in PHP, focusing primarily on removing keys and their corresponding values.

  1. unset() Function: The unset() function is used to remove a specific key along with its associated value from an associative array. This is demonstrated in the article by using unset($array['key']).

  2. Removing Multiple Keys: The unset() function can remove multiple keys by passing them as comma-separated arguments: unset($array['key1'], $array['key2']).

  3. array_diff() Function: This function compares arrays and returns the values from the first array that are not present in subsequent arrays. In the context of removing keys from an associative array, array_diff() can be used to create a new array excluding specified values.

  4. array_values() Function: The array_values() function creates a new array containing only the values from the original associative array. This effectively re-indexes the array numerically, removing the original keys but maintaining the order of values.

Understanding these concepts allows efficient manipulation and restructuring of associative arrays in PHP.

Regarding the provided code snippets:

  • The first set of code demonstrates the use of unset() to remove specific keys from the $mascots array.
  • The second set showcases array_diff() to generate a new array without specified values, effectively removing associated keys.
  • The final code block utilizes array_values() to create a new numerically indexed array containing only the values from the $mascots array, thus effectively removing all keys.

In summary, the article elucidates various techniques in PHP to remove keys and values from associative arrays, providing multiple options based on the specific needs of the developer in different scenarios.

Remove key and value from an associative array in PHP (2024)

FAQs

Remove key and value from an associative array in PHP? ›

The unset() function is used to unset a key and its value in an associative array. <? php // Declare an associative array $arr = array( "1" => "Add", "2" => "Multiply", "3" => "Divide" ); // Remove the key 1 and its value // from associative array unset($arr['1']); // Display the array elements print_r($arr); ?>

How to remove key and value from associative array in PHP? ›

Use unset() to remove an element by its key. 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.

How to remove the first key and value from an array in PHP? ›

The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).

How to separate array key and value in PHP? ›

PHP: array_chunk() function

The array_chunk() function is used to split an array into arrays with size elements. The last chunk may contain less than size elements. Specifies the array to split. If we set preserve_keys as TRUE, array_chunk function preserves the original array keys.

How to remove key and value from object in PHP? ›

The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change.

How to get key from associative array by value in PHP? ›

php // Use array_keys() function to display // the key of associative array // Associative array $assoc_array = array( "Geeks" => 30, "for" => 20, "geeks" => 10 ); // Using array_keys() function $key = array_keys($assoc_array); // Calculate the size of array $size = sizeof($key); // Using loop to access keys for( $i = ...

How to remove duplicate key from associative array in PHP? ›

Using array_unique() function

The array_unique() function in PHP removes duplicate values from an array by comparing the values and removing subsequent occurrences. It returns a new array with only unique values while preserving the original order of elements.

How to remove array key if value is empty in PHP? ›

We can also remove the empty value from an array using the PHP unset() function. The unset() function unset the variable. If the unset() function is called inside the user-defined function, then it can unset the value of the local variable. With the help of this function, we can remove the empty values from the array.

How do you remove empty key values from an array? ›

Answer: Use the PHP array_filter() function

You can simply use the PHP array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.

How to remove key-value from associative array in PHP? ›

The unset() function is used to unset a key and its value in an associative array. <? php // Declare an associative array $arr = array( "1" => "Add", "2" => "Multiply", "3" => "Divide" ); // Remove the key 1 and its value // from associative array unset($arr['1']); // Display the array elements print_r($arr); ?>

How to split an associative array in PHP? ›

How to split associative array in PHP? Use array_chunk() to split an associative array into chunks of a specified size, creating a multidimensional array.

How to find the key and value of an array in PHP? ›

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

How to remove keys from array map in PHP? ›

PHP Basics: All the ways to remove a key from a PHP array

Using the unset() function: $array = ['a', 'b', 'c']; unset($array[1]); This code removes the element with the key 1 from the $array array.

How to remove unique values from array in PHP? ›

The array_unique() function in PHP allows us to remove duplicate values from an array. It accepts an array as input and returns a new array with only unique elements. It is a useful tool for data cleaning and processing tasks in PHP. The array_unique() function was introduced in PHP version 4.0.

Top Articles
How Hunting Contributes to Wildlife Conservation
The Best Places for British Expats in 2024 | Intasure
What are Dietary Reference Intakes?
Rapv Springfield Ma
What is Cyber Big Game Hunting? - CrowdStrike
My.tcctrack
Roster Resource Orioles
1v1.LOL - Play Free Online | Spatial
Amazing deals for DKoldies on Goodshop!
PowerXL Smokeless Grill- Elektrische Grill - Rookloos & geurloos grillplezier - met... | bol
Universal Stone Llc - Slab Warehouse & Fabrication
Dragonvale Valor Dragon
Litter Robot 3 RED SOLID LIGHT
Obituaries Milwaukee Journal Sentinel
Webworx Call Management
Publix Near 12401 International Drive
Cfv Mychart
Unreasonable Zen Riddle Crossword
Craftybase Coupon
WPoS's Content - Page 34
Schooology Fcps
Bridgestone Tire Dealer Near Me
Aid Office On 59Th Ashland
Smartfind Express Henrico
Kstate Qualtrics
Skroch Funeral Home
Tyler Sis 360 Boonville Mo
T&J Agnes Theaters
Emerge Ortho Kronos
Empires And Puzzles Dark Chest
Section 212 at MetLife Stadium
11301 Lakeline Blvd Parkline Plaza Ctr Ste 150
Rhode Island High School Sports News & Headlines| Providence Journal
Fwpd Activity Log
Doublelist Paducah Ky
Costco Gas Foster City
Pink Runtz Strain, The Ultimate Guide
Watch Chainsaw Man English Sub/Dub online Free on HiAnime.to
Quiktrip Maple And West
Senior Houses For Sale Near Me
Caphras Calculator
Upcoming Live Online Auctions - Online Hunting Auctions
Mikayla Campinos Alive Or Dead
Wera13X
Uno Grade Scale
Prologistix Ein Number
Nfl Espn Expert Picks 2023
Room For Easels And Canvas Crossword Clue
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6312

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.