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

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

王林
Release: 2023-03-06 22:14:01
Original
4743 people have browsed it

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)
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template