php remove element from array
PHP : Remove object from array
12 Answers 12
You can also use spl_object_hash to create a hash for the objects and use that as array key.
However, PHP also has a native Data Structure for Object collections with SplObjectStorage :
On a sidenote, PHP also has native interfaces for Subject and Observer.
I agree with the answers above, but for the sake of completeness (where you may not have unique IDs to use as a key) my preferred methods of removing values from an array are as follows:
Which are used in the following way:
I recommend using the ID (if you have one, anything that will be unique to that object should work within reason) of the object as the array key. This way you can address the object within the array without having to run through a loop or store the ID in another location. The code would look something like this:
For remove an object from a multi dimensional array you can use this:
With array_column you can specify your key column name:
And this will remove the indicated object.
If you want to remove one or more objects from array of objects (using spl_object_hash to determine if objects are the same) you can use this method:
Reading the Observer pattern part of the GoF book? Here’s a solution that will eliminate the need to do expensive searching to find the index of the object that you want to remove.
Summary
Build in a way to find the element before assigning the object to the array. Otherwise, you will have to discover the index of the object element first.
If you have a large number of object elements (or, even more than a handful), then you may need to resort to finding the index of the object first. The PHP function array_search() is one way to start with a value, and get the index/key in return.
Do be sure to use the strict argument when you call the function.
If the third parameter strict is set to true then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.
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:
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.
How to remove the nth element from the end of an array
I know you can use the «array_pop» to remove the last element in the array. But if I wanted to remove the last 2 or 3 what would I do?
So how would I remove the last 2 elements in this array?
5 Answers 5
Use array_splice and specify the number of elements which you want to remove.
You can use array_slice() with a negative length :
In order to remove the last 2 elements of that array, you should use array_slice in this way:
as the rhyme goes: pop twice, or array_slice!
You can just use array_pop() twice. Run it like this:
The return value of array_pop() is the element you just removed, not the array. So if you don’t need that element anymore, simply call the function as many times as you need and move on.
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.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.