Home  >  Article  >  Backend Development  >  How to delete elements in a two-dimensional array in php

How to delete elements in a two-dimensional array in php

王林
王林Original
2020-11-02 10:11:104719browse

php method to delete elements in a two-dimensional array: You can use the array function array_splice to delete, such as [array_splice($arr, $index, 1);]. The array_splice function removes specified elements from an array and replaces them with new elements.

How to delete elements in a two-dimensional array in php

array_splice() function removes the selected element from an array and replaces it with a new element. The function will also return an array of removed elements.

(Video tutorial recommendation: php video tutorial)

Syntax:

array_splice(array,start,length,array)

Tips: If the function does not remove any elements (length=0) , the substitution array will be inserted from the position of the start parameter.

Note: Key names in the replacement array are not retained.

Code sample:

/**
     * 根据key删除数组中指定元素
     * @param  array  $arr  数组
     * @param  string/int  $key  键(key)
     * @return array
     */
private function array_remove_by_key($arr, $key) {
	if(!array_key_exists($key, $arr)) {
		return $arr;
	}
	$keys = array_keys($arr);
	$index = array_search($key, $keys);
	if($index !== FALSE) {
		array_splice($arr, $index, 1);
	}
	return $arr;
}

Related recommendations:php training

The above is the detailed content of How to delete elements in a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn