How to delete element in array php
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
How to delete element in array php
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string 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»!