How can I remove a key and its value from an associative array?
You can use unset
:
unset($array['key-here']);
Example:
$array = array("key1" => "value1", "key2" => "value2");
print_r($array);
unset($array['key1']);
print_r($array);
unset($array['key2']);
print_r($array);
Output:
Array
(
[key1] => value1
[key2] => value2
)
Array
(
[key2] => value2
)
Array
(
)
PHP - Remove and return an element from an associative array
Looking quickly at the official PHP documentation, in the current version (7.2) doesn't have a function that removes and returns an element by the key.
But as you mentioned there are several ways to solve this problem. As you can see at: https://stackoverflow.com/a/10898827/4214312
Deleting an element from an array in PHP
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a single array element
If you want to delete just one array element you can use unset()
or alternatively \array_splice()
.
If you know the value and don’t know the key to delete the element you can use \array_search()
to get the key. This only works if the element does not occur more than once, since \array_search
returns the first hit only.
unset()
Note that when you use unset()
the array keys won’t change. If you want to reindex the keys you can use \array_values()
after unset()
, which will convert all keys to numerically enumerated keys starting from 0.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete
Output:
[
[0] => a
[2] => c
]
\array_splice()
method
If you use \array_splice()
the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values()
, which will convert all keys to numerical keys.
\array_splice()
needs the offset, not the key, as the second parameter.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete
Output:
[
[0] => a
[1] => c
]
array_splice()
, same as unset()
, take the array by reference. You don’t assign the return values of those functions back to the array.
Deleting multiple array elements
If you want to delete multiple array elements and don’t want to call unset()
or \array_splice()
multiple times you can use the functions \array_diff()
or \array_diff_key()
depending on whether you know the values or the keys of the elements which you want to delete.
\array_diff()
method
If you know the values of the array elements which you want to delete, then you can use \array_diff()
. As before with unset()
it won’t change the keys of the array.
Code:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete
Output:
[
[1] => b
]
\array_diff_key()
method
If you know the keys of the elements which you want to delete, then you want to use \array_diff_key()
. You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete
Output:
[
[1] => b
]
If you want to use unset()
or \array_splice()
to delete multiple elements with the same value you can use \array_keys()
to get all the keys for a specific value and then delete all elements.
\array_filter()
method
If you want to delete all elements with a specific value in the array you can use \array_filter()
.
Code:
$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});
Output:
[
[0] => a
[1] => c
]
How to remove element from non-associative array in php
You can try this with array_search
-
unset($a[array_search('unset_me', $a)]);
If needed then add the checks like -
if(array_search('unset_me', $a) !== false) {
unset($a[array_search('unset_me', $a)]);
}
Demo
PHP Remove elements from associative array
Your array is quite strange : why not just use the key
as index, and the value
as... the value ?
Wouldn't it be a lot easier if your array was declared like this :
$array = array(
1 => 'Awaiting for Confirmation',
2 => 'Asssigned',
3 => 'In Progress',
4 => 'Completed',
5 => 'Mark As Spam',
);
That would allow you to use your values of key
as indexes to access the array...
And you'd be able to use functions to search on the values, such as array_search()
:
$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);
$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);
var_dump($array);
Easier than with your array, no ?
Instead, with your array that looks like this :
$array = array(
array('key' => 1, 'value' => 'Awaiting for Confirmation'),
array('key' => 2, 'value' => 'Asssigned'),
array('key' => 3, 'value' => 'In Progress'),
array('key' => 4, 'value' => 'Completed'),
array('key' => 5, 'value' => 'Mark As Spam'),
);
You'll have to loop over all items, to analyse the value
, and unset the right items :
foreach ($array as $index => $data) {
if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
unset($array[$index]);
}
}
var_dump($array);
Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?
Remove all elements of an associative array if they have the a specific word in the key
Filter the array by key:
$input = [
'TB1_course' => 'required',
'TB1_session' => 'required',
'TB2_course' => 'required',
];
$filter = function ($key) {
return substr($key, 0, 4) === 'TB2_';
};
$output = array_filter($input, $filter, ARRAY_FILTER_USE_KEY);
var_dump($output);
Output:
array(1) {
'TB2_course' =>
string(8) "required"
}
See http://php.net/array_filter for the documentation of the array_filter
function that is useful to filter arrays.
Associative array remove all values of 0
Well, there are a lot of ways to achieve this, out of which two I have mentioned below:
- Use array_filter.
Snippet:
<?php
$arr = [
'item1' => 0,
'item2' => 10,
'item5' => 0,
'item10' => 10,
'item12' => 5,
'item120' => false,
];
$filtered = array_filter($arr,function($value){
return $value !== 0;
});
print_r($filtered);
Demo: https://3v4l.org/fMsHt
- Another way I would suggest is to use array_diff()
Snippet:
<?php
$arr = [
'item1' => 0,
'item2' => 10,
'item5' => 0,
'item10' => 10,
'item12' => 5,
'item120' => false,
];
print_r(array_diff($arr,[0]));
Demo: https://3v4l.org/3YHiX
Php remove element from associative array with it's position
array_shift($arr);
For the array $arr = array('id' => 3, 'title' => 'lorem ipsum');
, this will return 3
and change the array $arr
to $arr = array('title' => 'lorem ipsum');
.
Docs: http://php.net/manual/en/function.array-shift.php
Related Topics
MySQL Alter Table Add Field Before or After a Field Already Present
Measure String Size in Bytes in PHP
How to Find Array/Dictionary Value Using Key
Making a Http Get Request with Http-Basic Authentication
How to Setup a Cron Job in Magento Module
How to Loop Through a Multidimensional Array Without Knowing It's Depth
How to Add Query Parameters in the Zf2/Zf3 Url View Helper
How to? Form Post to Multiple Locations
PHP How to Get the Base Domain/Url
PHP Curl Get Request and Request's Body
How to Bulk Update MySQL Data with One Query
Difference Between File, File_Get_Contents, and Fopen in PHP