How can I remove a key and its value from an associative array?
Given an associative array:
How would I go about removing a certain key-value pair, given the key?
7 Answers 7
Example:
Output:
Use this function to remove specific arrays of keys without modifying the original array:
First param pass all array, second param set array of keys to remove.
Consider this array:
To remove an element using the array key :
To remove element by value :
To remove an element by using index :
You may need two or more loops depending on your array:
you can do it using Laravel helpers:
first helper, method Arr::except:
second helper: method Arr::pull
Not the answer you’re looking for? Browse other questions tagged php arrays or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
PHP Remove elements from associative array
I have an PHP array that looks something like this:
When I var_dump the array values i get this:
Is there a way to remove them by matching the value name instead of the key value?
9 Answers 9
Wouldn’t it be a lot easier if your array was declared like this :
That would allow you to use your values of key as indexes to access the array.
Instead, with your array that looks like this :
Why do not use array_diff?
Just note that your array would be reindexed.
/edit As mentioned by JohnP, this method only works for non-nested arrays.
I kinda disagree with the accepted answer. Sometimes an application architecture doesn’t want you to mess with the array id, or makes it inconvenient. For instance, I use CakePHP quite a lot, and a database query returns the primary key as a value in each record, very similar to the above.
Assuming the array is not stupidly large, I would use array_filter. This will create a copy of the array, minus the records you want to remove, which you can assign back to the original array variable.
Although this may seem inefficient it’s actually very much in vogue these days to have variables be immutable, and the fact that most php array functions return a new array rather than futzing with the original implies that PHP kinda wants you to do this too. And the more you work with arrays, and realize how difficult and annoying the unset() function is, this approach makes a lot of sense.
You can use whatever inclusion logic (eg. your id field) in the embedded function that you want.
delete all values from an array while keeping keys intact
Do I really have to do this to reset an array?
13 Answers 13
Get an array of nulls with the same number of elements
Combine them, using keys and the keys, and the nulls as the values
As comments suggest, this is easy as of PHP 5.2 with array_fill_keys
Fill array with old keys and null values
$array = array_fill_keys(array_keys($array), null)
Define this function and call it whenever you need it:
There is no build-in function to reset an array to just it’s keys.
An alternative would be via a callback and array_map():
With regular callback function
Or with a lambda with PHP var_dump($array); outputs:
Flip the array to get the keys, then gives all keys the value NULL:
About array_fill_keys():
The array_fill_keys() function fills an array with values, specifying keys.
About array_flip():
The array_flip() function flips/exchanges all keys with their associated values in an array.
Wrap it in a [reusable] procedure:
Keep in mind though that PHP version starting from 5.3 pass values to functions by reference by default, i.e. the ampersand preceding argument variable in the function declaration is redundant. Not only that, but you will get a warning that the notion is deprecated.
If you need to nullify the values of a associative array you can walk the whole array and make a callback to set values to null thus still having keys
In case if you need to nullify the whole array just reassign it to empty one
unset would delete the key, You need to set the value to null or 0 as per your requirement.
I don’t get the question quite well, but your example
Why not making an array with required keys and asinging it to variable when you want reset it?
This is a fairly old topic, but since I referenced to it before coming up with my own solution for a more specific result, so therefore I will share with you that solution.
The desired result was to nullify all values, while keeping keys, and for it to recursively search the array for sub-arrays as well.
RECURSIVELY SET MULTI-LEVEL ARRAY VALUES TO NULL:
And here is it in use, along with BEFORE and AFTER output of the array contents.
PHP code to create a multilevel-array, and call the nullifyArray() function:
BEFORE CALL TO nullifyArray():
AFTER CALL TO nullifyArray():
I hope it helps someone/anyone, and Thank You to all who previously answered the question.
PHP: удаление элемента из массива
Я думал, что установка его на null сделал бы это, но, видимо, это не работает.
30 ответов
существуют различные способы удаления элемента массива, где некоторые из них более полезны для определенных задач, чем другие.
удалить один элемент массива
также, если у вас есть значение и не знаете ключ для удаления элемента, вы можете использовать array_search() получить ключ.
unset() метод
обратите внимание, что при использовании unset() ключи массива не изменятся/reindex. Если вы хотите переиндексировать ключи вы можете использовать array_values() после unset() который преобразует все ключи в числовые перечисляемые ключи, начиная с 0.
array_splice() метод
если вы используете array_splice() ключи будут автоматически переиндексируется, но ассоциативные ключи не будут меняться в отличие от array_values() который преобразует все ключи в числовые ключи.
и array_splice() требуется смещение, а не ключ! в качестве второго параметра.
array_splice() же unset() принять массив по ссылке, это означает, что вы не хотите присвоить возвращаемые значения этих функций в массив.
удалить несколько элементы массива
если вы хотите удалить несколько элементов массива и не хочу называть unset() или array_splice() несколько раз, вы можете использовать функции array_diff() или array_diff_key() в зависимости от того, знаете ли Вы значения или ключи элементов, которые вы хотите удалить.
array_diff() метод
array_diff_key() метод
также, если вы хотите использовать unset() или array_splice() для удаления нескольких элементов с одинаковым значением можно использовать array_keys() чтобы получить все ключи для определенного значения, а затем удалить все элементы.
следует отметить, что unset() сохранит индексы нетронутыми, чего и следовало ожидать при использовании строковых индексов (массив в качестве хэш-таблицы), но может быть довольно удивительно при работе с целочисленными индексированными массивами:
так array_splice() может использоваться, если вы хотите нормализовать целочисленные ключи. Другой вариант-использовать array_values() после unset() :
это вывод из кода выше:
теперь array_values () красиво переиндексирует числовой массив, но удалит все ключевые строки из массива и заменит их числами. Если вам нужно сохранить имена ключей (строки) или переиндексировать массив, если все ключи числовые, используйте array_merge ():
Если у вас есть численно индексированный массив, где все значения уникальны (или они не уникальны, но вы хотите удалить все экземпляры определенного значения), вы можете просто использовать array_diff () для удаления соответствующего элемента, например:
это отображает следующее:
в этом примере элемент со значением ‘Charles’ удаляется, что может быть проверено вызовами sizeof (), которые сообщают размер 4 для исходный массив, и 3 после удаления.
также для именованного элемента:
уничтожить один элемент массива
unset()
Если вам нужно повторно индексировать массив:
mixed array_pop(array &$array)
mixed array_shift ( array &$array )
чтобы избежать поиска, можно поиграть с array_diff :
в этом случае не нужно искать/использовать ключ.
unset() уничтожает указанные переменные.
поведение unset() внутри функции может варьироваться в зависимости от типа переменной, которую вы пытаетесь уничтожить.
если глобализованная переменная unset() внутри функции уничтожается только локальная переменная. Переменная в вызывающей среде сохранит то же значение, что и раньше unset() называлась.
ответ вышеуказанного кода будет бар
до unset() глобальная переменная внутри функции
Если вам нужно удалить несколько значений в массиве, а записи в этом массиве являются объектами или структурированными данными, [array_filter][1] это ваш лучший ставку. Те записи, которые возвращают true из функции обратного вызова будут сохранены.
ассоциативные массивы
числовые массивы
Примечание
Если вам нужно удалить несколько элементов из ассоциативного массива, вы можете использовать array_diff_key () (здесь используется с array_flip ()):
Я просто хотел сказать, что у меня был определенный объект, который имел переменные атрибуты (это было в основном отображение таблицы, и я менял столбцы в таблице, поэтому атрибуты в объекте, отражающие таблицу, также будут отличаться
цель $fields было просто так, что мне не нужно смотреть везде в коде, когда они меняются, я просто смотрю в начале класса и меняю список атрибутов и $fields содержимое массива для отражения новых атрибутов.
Мне потребовалось некоторое время, чтобы понять это. Надеюсь, это может кому-то помочь.
следуйте функциям по умолчанию
Предположим, у вас есть такой массив:
а также вы получаете:
unset () несколько фрагментированных элементов из массива
хотя unset() упоминалось здесь несколько раз, еще не упоминалось, что unset () принимает несколько переменных, что упрощает удаление нескольких несмежных элементов из массива за одну операцию:
unset () динамически
unset() не принимает массив ключей для удаления, поэтому приведенный ниже код завершится ошибкой (это сделало бы его немного проще использовать unset() динамически хотя.)
вместо этого unset () можно использовать динамически в цикле foreach:
удалите ключи массива, скопировав массив
очевидно, что такая же практика применяется к текстовым строкам:
решения:
далее объяснение:
использование этих функций удаляет все ссылки на эти элементы из PHP. Если вы хотите сохранить ключ в массиве, но с пустым значением, присвоить пустую строку к элементу:
помимо синтаксиса, есть логическая разница между использованием unset () и присвоение » элементу. Первый говорит: This doesn’t exist anymore, в то время как второй говорит This still exists, but its value is the empty string.
если вы имеете дело с числами, присвоение 0 может быть лучшая альтернатива. Таким образом, если компания остановила производство звездочки модели XL1000, она обновит свой инвентарь с помощью:
однако, если у него временно закончились звездочки XL1000, но он планировал получить новую партию с завода позже на этой неделе, это лучше:
если вы unset () элемент, PHP настраивает массив так, чтобы цикл все еще работал правильно. Он не компактирует массив, чтобы заполнить недостающие отверстия. Этот это то, что мы имеем в виду, когда говорим, что все массивы ассоциативны, даже когда они кажутся числовыми. Вот пример:
чтобы сжать массив в плотно заполненный числовой массив, используйте array_values ():
кроме того, array_splice () автоматически оленей массивы, чтобы избежать оставляя отверстия:
это полезно, если вы используете массив в очереди и хотите, чтобы удалить элементы из очереди в то же время позволяя случайный доступ. Чтобы безопасно удалить первый или последний элемент из массива, используйте array_shift () и array_pop (), соответственно.
PHP array delete by value (not key)
I have a PHP array as follows:
I’m looking for the simplest function to perform this task, please.
20 Answers 20
The if() statement will check whether array_search() returned a value, and will only perform an action if it did.
Well, deleting an element from array is basically just set difference with one element.
It generalizes nicely, you can remove as many elements as you like at the same time, if you want.
Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.
One interesting way is by using array_keys() :
The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).
This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4] ).
If you know for definite that your array will contain only one element with that value, you can do
If, however, your value might occur more than once in your array, you could do this
Note: The second option only works for PHP5.3+ with Closures
Or simply, manual way:
This is the safest of them because you have full control on your array
Output
Array ( [0] => 312 [1] => 1599 [2] => 3 )
With PHP 7.4 using arrow functions:
To keep it a non-associative array wrap it with array_values() :
Explanation: Delete the element that has the key 401 after flipping the array.
To delete multiple values try this one:
The accepted answer converts the array to associative array, so, if you would like to keep it as a non-associative array with the accepted answer, you may have to use array_values too.
Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)
array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)
array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)
So in our current example we can use the above functions as follows:
or even better: (as this give us a better syntax to use like the array_filter one)
The above can be used for more complicated stuff like let’s say we would like to remove all the values that are greater or equal to 401 we could simply do this:




















