Как обнулить массив php
Лучший способ очистить значения массива PHP
Что более эффективно для очистки всех значений в массиве? Первый из них потребовал бы, чтобы я использовал эту функцию каждый раз в цикле второго примера.
Как сказал Зак в комментариях ниже, вы можете просто повторно создать его, используя
Если вы просто хотите сбросить переменную в пустой массив, вы можете просто повторно инициализировать ее:
Обратите внимание, что это будет содержать ссылки на него:
Если вы хотите разорвать любые ссылки на него, сначала отключите его:
К сожалению, я не могу ответить на другие вопросы, не имею достаточной репутации, но мне нужно указать что-то, что было ОЧЕНЬ важно для меня, и я думаю, что это поможет другим людям.
Сброс переменной – отличный способ, если вам не нужна ссылка на исходный массив!
Чтобы понять, что я имею в виду: если у вас есть функция, использующая ссылку массива, например функцию сортировки, например
Я бы сказал, первый, если массив ассоциативный. Если нет, используйте цикл for :
Хотя, если это возможно, использование
Предпочтительным является сброс массива в пустой массив.
Не unset() достаточно хорошо?
Используйте array_splice для array_splice массива и сохранения ссылки:
Функция unset полезна, когда сборщик мусора делает свои раунды, не имея перерыва на обед;
однако функция unset просто уничтожает ссылку на переменные для данных, данные все еще существуют в памяти, и PHP видит, что память используется, несмотря на то, что у нее больше нет указателя на нее.
Решение. Назначьте null своим переменным, чтобы очистить данные, по крайней мере до тех пор, пока сборщик мусора не схватит его.
а затем отключить его аналогичным образом!
я использовал unset (), чтобы очистить массив, но я понял, что unset () будет отображать массив null, следовательно, необходимо повторно объявить массив, например, например
// делай то, что хочешь здесь
Это мощный и проверенный unset ($ gradearray); // повторно задает массив
reset
(PHP 4, PHP 5, PHP 7, PHP 8)
reset — Устанавливает внутренний указатель массива на его первый элемент
Описание
reset() перемещает внутренний указатель массива array к его первому элементу и возвращает значение первого элемента массива.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования reset()
Примечания
Смотрите также
User Contributed Notes 13 notes
GOTCHA: If your first element is false, you don’t know whether it was empty or not.
?>
So don’t count on a false return being an empty array.
As for taking first key of an array, it’s much more efficient to RESET and then KEY, rather then RESET result of ARRAY_KEYS (as sugested by gardnerjohng at gmail dot com).
Also it’s good to reset this way the multidimentional arrays:
Note that reset() will not affect sub-arrays of multidimensional array.
In response to gardnerjohng’s note to retrieve the first _key_ of an array:
To retrieve the first _key_ of an array you can use the combination of reset() and key().
Since reset() returns the first «value» of the array beside resetting its internal pointer; it will return different results when it is combined with key() or used separately. Like;
?>
This is perfectly normal because in the first method, reset() returned the first «value» of the ‘biscuits’ element which is to be «cbosi». So key(string) will cause a fatal error. While in the second method you just reset the array and didn’t use a returning value; instead you reset the pointer and than extracted the first key of an array.
If your array has more dimensions, it won’t probably cause a fatal error but you will get different results when you combine reset() and key() or use them consecutively.
Following code gives a strict warning in 5.4.45
«Strict warning: Only variables should be passed by reference»
$keys = array_keys($result[‘node’]);
return reset($keys);
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason. The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.
The following code demonstrates the resetting of a subarray:
Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings. Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.
So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.
Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
Массивы в PHP
Что такое массив
Например, так можно объявить массив с тремя значениями:
Массивы также отлично подходят для объединения нескольких связанных между собой значений, например характеристик товара:
Создание массива
Для создания пустого массива просто укажите квадратные скобки вместо значения:
Результат в браузере:
PHP сообщает нам, что в переменной лежит массив (англ. array), в котором находится 0 значений.
Чтобы объявить массив с данными, просто перечислите значения в квадратных скобках:
Создание массивов с помощью квадратных скобок работает начиная с версии PHP 5.4. До этого использовался более громоздкий синтаксис:
Ключи и значения массива
Массив состоит из ключей (индексов) и соответствующих им значений. Это можно представить как таблицу:
| Ключ | Значение |
|---|---|
| 0 | Samsung |
| 1 | Apple |
| 2 | Nokia |
У каждого значения есть свой ключ. В массиве не может быть несколько одинаковых ключей.
Вернёмся к предыдущему примеру и посмотрим, что лежит в массиве:
Результат в браузере:
Когда мы создаём массив без указания ключей, PHP генерирует их автоматически в виде чисел, начиная с 0.
Указание ключей происходит с помощью конструкции => :
Простые и ассоциативные массивы
Когда мы создаём массив с числовыми ключами, такой массив называется простым или числовым.
Вывод массива
Вывод элементов массива выглядит следующим образом:
Однако обе функции выводят информацию на одной строке, что в случае с массивами превращается в кашу. Чтобы этого не происходило, используйте тег ‘;
Результат в браузере:
Также вывести содержимое массива можно с помощью цикла foreach:
Подробней работу цикла foreach мы разберём в отдельном уроке.
Добавление и удаление элементов
Добавление новых элементов в массив выглядит следующим образом:
Но если название ключа не играет роли, его можно опустить:
Удалить элемент массива можно с помощью функции unset() :
Двумерные и многомерные массивы
В качестве значения массива мы можем передать ещё один массив:
Обратиться к элементу многомерного массива можно так:
Теперь мы можем хранить в одном массиве целую базу товаров:
Или альтернативный вариант:
Задача 1
Задача 2
2. Создайте подмассив streets с любыми случайными улицами. Каждая улица должна иметь имя (name) и количество домов (buildings_count), а также подмассив из номеров домов (old_buildings), подлежащих сносу.
Лучший способ очистить значения массива PHP
Что более эффективно для очистки всех значений в массиве? Первый потребовал бы, чтобы я использовал эту функцию каждый раз в цикле второго примера.
ОТВЕТЫ
Ответ 1
Как сказал Зак в комментариях ниже, вы можете просто повторно создать его, используя
Ответ 2
Если вы просто хотите reset указать переменную в пустой массив, вы можете просто повторно инициализировать ее:
Обратите внимание, что это будет содержать ссылки на него:
Если вы хотите разорвать любые ссылки на него, сначала отмените его:
Ответ 3
К сожалению, я не могу ответить на другие вопросы, не имею достаточной репутации, но мне нужно указать что-то, что было ОЧЕНЬ важно для меня, и я думаю, что это поможет другим людям.
Чтобы понять, что я имею в виду: Если у вас есть функция, использующая ссылку массива, например функцию сортировки, например
Ответ 4
Я бы сказал, первый, если массив ассоциативный. Если нет, используйте цикл for :
Если возможно, используя
В reset предпочтительнее использовать массив в пустом массиве.
Ответ 5
Ответ 6
Ответ 7
Ответ 8
Функция unset полезна, когда сборщик мусора делает свои раунды, не обедая break;
однако функция unset просто уничтожает ссылку на переменные для данных, данные все еще существуют в памяти, и PHP видит, что память используется, несмотря на то, что у нее больше нет указателя на нее.
Решение: Присвойте null вашим переменным, чтобы очистить данные, по крайней мере, до тех пор, пока сборщик мусора не схватит его.
а затем отключите его аналогичным образом!
Ответ 9
Я использовал unset(), чтобы очистить массив, но я понял, что unset() будет отображать массив null, следовательно, необходимо повторно объявить массив, например,
//делай, что хочешь здесь
Ответ 10
Это мощный и проверенный unset ($ gradearray);//повторно установить массив
unset
(PHP 4, PHP 5, PHP 7, PHP 8)
unset — Удаляет переменную
Описание
unset() удаляет перечисленные переменные.
Поведение unset() внутри пользовательской функции может отличаться, в зависимости от того, какой тип имеет переменная, которую необходимо удалить.
Результат выполнения данного примера:
Результат выполнения данного примера:
Если статическая переменная удаляется внутри функции, unset() удалит переменную только в контексте дальнейшего выполнения функции. При последующем вызове предыдущее значение переменной будет восстановлено.
Результат выполнения данного примера:
Список параметров
Возвращаемые значения
Функция не возвращает значения после выполнения.
Примеры
Пример #1 Пример использования unset()
Пример #2 Использование приведения типа (unset)
Результат выполнения данного примера:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Существует возможность удалить даже атрибуты объекта, видимые в текущем контексте.
При использовании unset() на недоступных или необъявленных свойствах объекта, будет вызван встроенный метод объекта __unset(), если он определён.
Смотрите также
User Contributed Notes 31 notes
This doesn’t apply to properties of objects that have __isset() methods that visibly change object state or __unset() methods that don’t properly check their arguments or have extra side effects.
The latter case means that __unset shouldn’t do more than what it says on the tin, and also has the responsibility for checking (possibly using __isset()) that what it’s being asked to do makes sense.
The former case is just plain bad design.
if you try to unset an object, please be careful about references.
Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object. sigh!
class A <
function __destruct () <
echo «cYa later!!\n» ;
>
>
echo «Finally that thing is gone\n» ;
?>
Of course the object completely dies at the end of the script.
Since unset() is a language construct, it cannot be passed anything other than a variable. It’s sole purpose is to «unset» this variable, ie. to remove it from the current scope and destroy it’s associated data. This is true especially for reference variables, where not the actual value is destroyed but the reference to that value. This is why you can’t wrap ‘unset()’ in a user defined function: You would either unset a copy of the data if the parameter is passed by value, or you would just unset the reference variable within the functions scope if the parameter is passed by reference. There is no workaround for that, as you cannot pass ‘scope’ to a function in PHP. Such a function can only work for variables that exist in a common or global scope (compare ‘unset($_GLOBALS[variable])’).
I don’t know how PHP handles garbage collection internally, but I guess this behavior can result in a huge memory leak: if a value variable goes out of scope with a second variable still holding a reference to the in-memory value, then unsetting that reference would still hold the value in memory but potentially unset the last reference to that in-memory data, hence: occupied memory that is rendered useless as you cannot reference it anymore.
A sample how to unset array elements from an array result coming from a mysql request. In this sample it is checking if a file exists and removes the row from the array if it not exists.
1.
it gets the array from the table (mysql)
3.
unset if record does not exist
Here is another way to make ‘unset’ work with session variables from within a function :
Only This works with register_globals being ‘ON’.
The above will not work with register_globals turned on (will only work outside of a function).
The above will work with register_globals on & inside a function
To clarify what hugo dot dworak at gmail dot com said about unsetting things that aren’t already set:
unsetting a non-existent key within an array does NOT throw an error.
Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of the array, if you use unset, the next index value will still be what it would have been.
but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )
This is since even though the last key is removed, the auto indexing still keeps its previous value.
The only time where this would not seem right is when you remove a value off the end. I guess different people would want it different ways.
Hope this helps someone who may need this for some odd reason, I did.
In addition to what timo dot hummel at 4fb dot de said;
>For the curious: unset also frees memory of the variable used.
>
>It might be possible that the in-memory size of the PHP Interpreter isn’t reduced, but your scripts won’t touch the memory_limit boundary. Memory is reused if you declare new variables.
It might be worth adding that functions apparently don’t free up memory on exit the same way unset does..
Maybe this is common knowledge, but although functions destroys variables on exit, it (apparently) doesn’t help the memory.
So if you use huge variables inside functions, be sure to unset them if you can before returning from the function.
In my case, if I did not unset before return, then the script would use 20 MB more of memory than if I did unset.
This was tested with php 5.0.4 on apache 2 on windows xp, with no memory limit.
Before I did the test, I was under the impression that when you exit from functions, the memory used inside it would be cleared and reused. Maybe this should be made clear in the manual, for either unset() or in the chapter for functions.
Despite much searching, I have not yet found an explanation as to how one can manually free resources from variables, not so much objects, in PHP. I have also seen many comments regarding the merits and demerits of unset() versus setting a variable to null. Thus, here are the results of some benchmarks performed comparing unset() of numerous variables to setting them to null (with regards to memory usage and processing time):
10 variables:
Unset:
Memory Usage: 296
Time Elapsed: 1.0013580322266E-5
Null set:
Memory Usage: 1736
Time Elapsed: 5.9604644775391E-6
50 variables:
Unset:
Memory Usage: 296
Time Elapsed: 3.6001205444336E-5
Null set:
Memory Usage: 8328
Time Elapsed: 3.2901763916016E-5
100 variables:
Unset:
Memory Usage: 296
Time Elapsed: 5.6982040405273E-5
Null set:
Memory Usage: 15928
Time Elapsed: 5.8174133300781E-5
1000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.00041294097900391
Null set:
Memory Usage: 168096
Time Elapsed: 0.00067591667175293
10000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.0042569637298584
Null set:
Memory Usage: 1650848
Time Elapsed: 0.0076930522918701
100000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.042603969573975
Null set:
Memory Usage: 16249080
Time Elapsed: 0.087724924087524
300000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.13177299499512
Null set:
Memory Usage: 49796320
Time Elapsed: 0.28617882728577
Perhaps my test code for the null set was flawed, but despite that possibility it is simple to see that unset() has minimal processing time impact, and no apparent memory usage impact (unless the values returned by memory_get_usage() are flawed). If you truly care about the
4 microseconds saved over
In PHP 5.0.4, at least, one CAN unset array elements inside functions from arrays passed by reference to the function.
As implied by the manual, however, one can’t unset the entire array by passing it by reference.
Note that PHP 4 will generate a warning if you try to unset an array index that doesn’t exist and whose parent doesn’t exist.
?>
RESULT: «Notice: Undefined index: Bar»
On PHP5 no error is raised, which seems to me like the correct behaviour.
Note that using unset($foo[‘Bar’]) in the above example does not generate a warning in either version.
(Tested on 4.4.9 and 5.2.4)
Just to confirm, USING UNSET CAN DESTROY AN ENTIRE ARRAY. I couldn’t find reference to this anywhere so I decided to write this.
The documentation is not entirely clear when it comes to static variables. It says:
If a static variable is unset() inside of a function, unset() destroys the variable and all its references.
The above example would output:
And it does! But the variable is NOT deleted, that’s why the value keeps on increasing, otherwise the output would be:
The references are destroyed within the function, this handeling is the same as with global variables, the difference is a static variable is a local variable.
Be carefull using unset and static values as the output may not be what you expect it to be. It appears to be impossible to destroy a static variable. You can only destroy the references within the current executing function, a successive static statement will restore the references.
The documentation would be better if it would say:
«If a static variable is unset() inside of a function, unset() destroys all references to the variable. «
Here’s my variation on the slightly dull unset method. It throws in a bit of 80’s Stallone action spice into the mix. Enjoy!
/**
* function rambo (first blood)
*
* Completely and utterly destroys everything, returning the kill count of victims
*
* @param It don’t matter, it’s Rambo baby
* @return Integer Body count (but any less than 500 and it’s not really worth mentioning)
*/
function rambo () <
// Get the victims and initiate that body count status
$victims = func_get_args ();
$body_count = 0 ;
about unset for arrays
if you unset the last array member
$ar[0]==2
$ar[1]==7
$ar[2]==9
So, unset has no effect to internal array counter.
further I realized that an object, when getting detroyed, does care about destroying variable in object space visibility but not those in local visibility, be aware of the found pattern:
Instead of using the unset function for unregistering your session or other array values you can also do this samll feature and get this task done with just 1 line code.
Suppose, if you like to unregister your session store values.
You can use:
Well this syntax saves lot’s of time instead of unsetting each values.
you may wan’t to unset all variables which are defined, here’s one way:
?>
you can also save than a serialized var of the «memory» and perhaps store this in a temporary file.. very usefull if you work with text files and/or file uploads when you’ve got very large variables.
When unset from an array, if you unset all elements, the array is always set
In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don’t exist.
Sometimes you need to assigne values to an array index in some loop (if, while, foreach etc.) but you wish to set starting index key to some number greater then zero (lets say 5). One idea how to do this is:
Array ( [5] => 5 [6] => 10 [7] => 15 [8] => 100 )
You can not unset a numeric key of an array, if key is a string. See this example:
And here is the output:
Test: 1
array(3) <
[10]=>
array(1) <
[0]=>
string(6) «apples»
>
[20]=>
array(1) <
[0]=>
string(7) «bananas»
>
[30]=>
array(1) <
[0]=>
string(7) «peaches»
>
>
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) <
>
Two ways of unsetting values within an array:
$SomeObj = new TheObj ;
This applied to the «virtual» array variable too, see more at http://bugs.php.net/bug.php?id=33513 (at feedback) about it.
PS: we used PHP version 5.1.0-dev from the CVS snapshot when we wrote the above codes.
1) unsetting of superglobals is done globally, i.e. unsetting inside the function affects GLOBALLY.
foo ();
bar (); //issues E_NOTICE ($GLOBALS not defined)
$GLOBALS = 3 ;
bar (); //displays int(3)