Join my Laravel for REST API's course on Udemy 👀

Remove key and value from an associative array in PHP

May 9, 2022  ‐ 3 min read

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

<?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.

<?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).

<?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.

<?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.