Php unset удалить элемент массива

How to delete a specific element from an array in PHP

In this article, you will learn how to delete an element from an array using PHP. We will cover different methods to do it on different types of arrays with multiple examples.

Before going further, let’s cover how the three functions that we will need later work.

The unset() function

The unset() function is an in-built function in PHP used to unset/destroy a given variable or a set of variables.

Syntax

Parameters

The function requires at least one variable as the parameter, but you can pass multiple variables that you want to unset, separated with commas.

The unset() function has no return value.

After a variable is unset, the program behaves as if the variable never existed and no longer recognizes it. If you unset a variable then try to use it again in your program, the system gives the undefined variable error.

If the unset() function is called inside a user-defined function, it unsets only the local variables. If you want to unset a global variable inside the function (one that is initialized outside it), then you have to use the $GLOBALS array to do so.

The array_splice() function

The array_splice() function is in-built in PHP and removes the selected elements from an array and replaces them with new elements.

Syntax

array_splice(array1, start, length, array2)

Parameters

The array_values() function

The array_values() is an in-built PHP function that re-indexes an array and returns it with numeric keys, starting at 0 and increasing by 1.

Syntax

The array is a required parameter that specifies the array to be worked on.

How to delete an element from an array in PHP

Method 1: Using the unset() function

The unset() function can be used to destroy a whole array in a variable, or a specified element in the array using its index or key.

Unlike for the ordinary variables where we just pass the variable name to the function, to delete a specific element from the array and leave its other elements intact, we have to include the element index or key to the array variable when passing it to the unset() function.

Example 1

Deleting an element from a numerically indexed array based on its index.

"; print_r ($fruits); echo "
"; unset($fruits[1]); echo "The array after deleting an element
"; print_r ($fruits);

The array before deleting an element
Array ( [0] => Apple
[1] => Mango
[2] => Avocado
[3] => Banana
[4] => Watermelon
[5] => Passion
)
The array after deleting an element
Array ( [0] => Apple
[2] => Avocado
[3] => Banana
[4] => Watermelon
[5] => Passion
)

Читайте также:  Аналог readln в питоне

The array indices start from 0. So array element with an index of 1 is actually the second element in the array. We have passed the array name with index 1 to the unset() function. From the output, you can see the second element (Mango) has been deleted from the array.

One thing you can note from the above example is that after deleting the element with index 1, the function keeps the other indices untouched, ie index one is missing with the resulting array starting with index 0 followed by 2. The unset() function doesn’t re-index the array after deleting an element from a numerically indexed array.

To fix that and have the resulting array re-indexed, all you need to do is pass the array to the array_values() function.

Example 2

Re-indexing a numeric array using array_values() function after deleting an element with the unset() function.

The array before deleting an element
Array ( [0] => Apple
[1] => HP
[2] => Dell
[3] => Lenovo
)

As you can see from the output, we have deleted «Toshiba» which occupied index 2 of the array. After passing the array to the array_values() function, it has been re-indexed to have «Dell» shift from index 3 to 2 and «Lenovo» from index 4 to 3.

Example 3

Deleting an element from an associative array based on its key.

 "John Doe", "email" => "johndoe@gmail.com", "age" => 28); echo "The array before deleting an element 
"; print_r ($person); echo "
"; unset($person["age"]); echo "The array after deleting an element
"; print_r ($person);

The array before deleting an element
Array ( [name] => John Doe
[email] => johndoe@gmail.com
[age] => 28
)
The array after deleting an element
Array ( [name] => John Doe
[email] => johndoe@gmail.com
)

As you can see the age element has been deleted from the array.

If you know an array element value and don’t know its key/index but you want to delete it, you can do so y first using the array_search() function to get its key, then use that key to delete it.

You pass two parameters to the array_search() function where the first is the value whose key you want to know, and the second is the actual array from which you are searching the value. The function returns the key/index of the array element with that value.

The key for Watermelon is: 4

Example

"; print_r ($laptops); echo "
"; unset($laptops[array_search("Dell", $laptops)]); echo "The array after deleting an element
"; print_r ($laptops);

The array before deleting an element
Array ( [0] => Apple
[1] => HP
[2] => Toshiba
[3] => Dell
[4] => Lenovo
)
The array after deleting an element
Array ( [0] => Apple
[1] => HP
[2] => Toshiba
[4] => Lenovo
)

From the example above, we have used the array_search() function with value «Dell» to find the index of the array element that matches it, then used that index to delete the element using the unset() function. You can from the output it has worked because «Dell» was deleted from the array.

Method 2: Using the array_splice() function

This function removes a specified range of array elements and re-indexes the array numerically automatically.

Читайте также:  Тип данных int kotlin

As opposed to the unset() function, the array_splice() needs the offset as the second parameter and not an array key of the element in the array variable.

Example 1

"; print_r ($companies); echo "
"; array_splice($companies, 3, 1); echo "The array after deleting an element
"; print_r ($companies);

The array before deleting an element
Array ( [0] => SpaceX
[1] => Apple
[2] => Google
[3] => Tesla
[4] => Microsoft
)
The array after deleting an element
Array ( [0] => SpaceX
[1] => Apple
[2] => Google
[3] => Microsoft
)

The offset (start) parameter starts counting values from 0, the same way as array indices. To delete «Tesla», which is the fourth element, we had to use offset 3 and 1 for the length parameter since we only wanted to delete one element.

If for instance, we wanted to delete both Tesla and Microsoft, we would have used array_splice($companies, 3, 2) instead. 3 specifying the deletion to start from the fourth element, and 2 specifying the number of elements to be deleted.

As opposed to the unset() function which leaves the array indices untouched, you can see from the example above the array_splice() has re-indexed the array elements after the deletion.

Example 2

Deleting an element from an associative array using the array_splice() function.

 "John Doe", "email" => "johndoe@gmail.com", "age" => 28); echo "The array before deleting an element 
"; print_r ($person); echo "
"; array_splice($person, 1, 1); echo "The array after deleting an element
"; print_r ($person);

The array before deleting an element
Array ( [name] => John Doe
[email] => johndoe@gmail.com
[age] => 28
)
The array after deleting an element
Array ( [name] => John Doe
[age] => 28
)

The second element (email), whose offset is 1 has been deleted from the example above.

Now you know how to delete specific elements from arrays in PHP.

Источник

Как удалить элемент массива в PHP?

Одним из мощнейших инструментов PHP-разработчика являются массивы. Если вы работали с массивами в других языках программирования (Delphi, Fortrain, C++), то помните, что везде массив надо объявлять, указывая размерность и тип элементов. В PHP всё обстоит иначе.

Дело в том, что в PHP массив не является линейным объектом. Это, по сути, хеш-массив, представляющий собой набор пар — ключей с их значениями.

Теперь давайте посмотрим, как удалять элементы из хеш-массива в PHP. В вышеупомянутых языках программирования для таких действий придётся создавать специальный объект, односвязный либо 2-связный список, бережно выделять и освобождать память, наблюдать за восстановлением связей в списке. Что касается PHP, то тут весь необходимый «менеджмент» спрятан, но всегда готов к применению.

1. Удаляем элемент массива в PHP

Чтобы удалить элемент в PHP, достаточно всего лишь знать его ключ — в таком случае удаление будет сведено к вызову функции unset() :

 
php $a = array('a','b','c'); unset($a[1]); //удаляем элемент с ключом «1» print_r($a); //на экране отобразится: Array ( [0] => a [2] => c ) ?> 

2. Как удалить 1-й элемент массива?

Если не знаем ключ, но знаем, что удалять надо 1-й элемент массива, подойдёт функция array_shift() . Она извлечёт значение 1-го элемента, удалит его из массива и выполнит перенумерацию числовых ключей, начав с нуля.

 
php $stack = array(3 => 'a', 5 => 'b', 'third element' => 'c'); $elm = array_shift($stack); print_r($stack); //на экране отобразится: Array ( [0] => b [third element] => c ) ?> 

В нашем случае 1-й элемент удаляется, а элемент 5 => ‘b’, попадает под перенумерацию. Что касается элементов со строковыми ключами, то их перенумерация не затронет.

3. Как удалить последний элемент массива?

Схожим образом выполняют удаление последнего элемента массива. Для этого в PHP есть функция array_pop() .

 
php $stack = array(3 => 'a', 5 => 'b', 'third element' => 'c'); $elm = array_pop($stack); print_r($stack); //на экране отобразится: Array ( [3] => a [5] => b ) ?> 

После удаления последнего элемента массива в PHP перенумерация оставшихся элементов не выполняется.

4. Как удалить пустые элементы из массива?

Сначала вспомним, что называют пустым элементом. Лучше всего определить «пустое значение» помогает результат работы функции empty() . Функция возвратит true для пустого элемента, причем не только скалярного. Убедимся в этом на примере ниже:

 
php $stack = array(3 => 'a', 5 => 'b', '3rd' => 'c', array(), null, false, 0, '', '0', '00'); foreach ($stack as $k => $v) if (empty($v)) unset($stack[$k]); print_r($stack); //на экране отобразится : Array ( [3] => a [5] => b [3rd] => c [12] => 00 ) ?> 

Итак, мы в цикле проверим каждый элемент массива, используя функцию empty() и удалим пустые элементы. Здесь важно понять, что строковый скаляр ‘0’ — тоже пустой элемент. А вот ’00’ пустым не является.

Если считаете, что поэлементная проверка массива — неоптимальный вариант, воспользуйтесь функцией сравнения массивов в PHP — array_diff() , перечислив с её помощью все элементы, которые считаем «нулевыми»:

 
php $stack = array(3 => 'a', 5 => 'b', '3rd' => 'c', array(), null, false, 0, '', '0', '00', ' '); $stack = array_diff($stack, array(array(), null, false, 0, '', '0', '00', ' ')); print_r($stack); //на экране отобразится: Array ( [3] => a [5] => b [3rd] => c ) ?> 

Очевидно, что данный способ более гибок.

5. Удаляем повторяющиеся элементы массива в PHP

Порой возникает необходимость удалить повторяющиеся элементы массива в PHP. Для решения этой задачи существует специальная функция под названием array_unique() :

 
php $stack = array('a', 'b', 'b', 'c', 'c', 0, '0'); $stack = array_unique($stack); print_r($stack); //на экране отобразится: Array ( [0] => a [1] => b [3] => c [5] => 0 ) ?> 

Из кода видно, что функция удалила из PHP-массива повторяющиеся элементы. При этом функция имеет ещё один параметр, указывающий, как сравнивать элементы.

Возможные типы сравнения: • SORT_REGULAR — сравнение без преобразования типа элементов; • SORT_STRING — сравнение как строки; • SORT_NUMERIC — сравнение как чисел (пытаемся преобразовать в число); • SORT_LOCALE_STRING — сравнение как строки, но с учётом выбранного набора символов.

По умолчанию применяется SORT_STRING. Выбирая типы сравнения, помните, что это важно. Давайте изменим тип в прошлом примере на SORT_NUMERIC:

 
php $stack = array('a', 'b', 'b', 'c', 'c', 0, '0'); $stack = array_unique($stack, SORT_NUMERIC); print_r($stack); //на экране отобразится: Array ( [0] => a ) ?> 

Во время сравнения все элементы массива были преобразованы к численному типу скаляра. В нашем случае это неизменно давало значение ноль, в результате чего у нас остался лишь первый элемент.

Хотите знать о PHP больше? Записывайтесь на курс «Backend-разработчик на PHP»!

Источник

Оцените статью