Home >Backend Development >PHP Tutorial >Several PHP methods to delete array elements_PHP tutorial

Several PHP methods to delete array elements_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:01:551051browse

Several PHP methods for deleting array elements. In many cases, our arrays will be duplicated. So what should we do if we delete some duplicate contents in the array? I must keep these elements unique, so I thought of ways to delete them. The following is used Several ways to iterate over a query to remove duplicate array elements. ​

Several PHP tutorials on how to delete array elements
In many cases, our arrays will be duplicated. So what should we do if we delete some duplicate contents in the array? I must keep these elements unique, so I find a way to delete them. The following uses a traversal query to delete duplicate array elements. several methods.


Take a look at a complete example of deleting duplicate arrays


//Delete an element in the array
function array_remove_value(&$arr, $var){
foreach ($arr as $key => $value) {
if (is_array($value)) {
array_remove_value($arr[$key], $var);
} else {
$value = trim($value);
if ($value == $var) {
unset($arr[$key]);
} else {
$arr[$key] = $value;
}
}
}
}


$a is an array:
count($a); //get 4
unset($a[1]); //Delete the second element
count($a); //get 3
echo $a[2]; //There are only three elements in the array. I wanted to get the last element, but I got blue,
echo $a[1]; //No value
?>
That is to say, after deleting the elements in the array, the number of elements in the array (obtained with count()) has changed, but the array subscripts have not been rearranged, and the corresponding values ​​must be operated with the key before deleting the array.
Later, I adopted another method, which is actually not called a "method" at all. I used the ready-made function array_splice() in php4.
count ($a); //Get 4
array_splice($a,1,1); //Delete the second element
count ($a); //Get 3
echo $a[2]; //get yellow
echo $a[1]; //get blue
?>


Method 2

Function to delete duplicate elements in an array
function delmember(&$array, $id)
{
$size = count($array);
for($i = 0; $i <$size - $id - 1; $i ++)
{
$array[$id + $i] = $array[$id + $i + 1];
}
unset($array[$size - 1]);
}


For more details, please see: http://www.bkjia.com/phper/php-function/34794.htm


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445404.htmlTechArticleSeveral PHP methods to delete array elements. In many cases, our arrays will be duplicated, so we delete them in the array. What to do with some repeated content, I must keep these elements unique...
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