A few instructions on removing duplicate elements from an array in php_PHP Tutorial

WBOY
Release: 2016-07-21 15:48:40
Original
1002 people have browsed it

For example:

Copy code The code is as follows:

$test_array=array(1,2,3,4,4,5 ,5,6);
$test_array_unique=array_unique($test_array);
print_r($test_array_unique);
$test_array=array(1,2,3,4,4,5,5,6 );
$test_array_unique=array_unique($test_array);
print_r($test_array_unique);
But now, don’t be careless, it’s not over yet. If you look carefully, you will find that although the repeated elements have been removed, the indexes of the remaining elements have not changed. In this case, if you use a for loop to call this array element, an error will occur, because the for loop is based on The number is increasing, and most people use count($test_array_unique) to get the size of the array, which will cause some elements to be missed;
Copy code The code is as follows:

$test_array=array(1,2,3,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
for ($i=0;$i{
echo $test_array_unique[$i];
}
$test_array=array(1,2,3 ,4,4,5,5,6);
$test_array_unique=array_unique($test_array);
for($i=0;$i{
echo $test_array_unique[$i];
}
This way you will not see element 6 being output, because the index of 6 is 8, the array before processing and the array index after processing do not Any changes;
Solution:
Of course, there are too many solutions here. I only introduced a method that I think is relatively simple, which is the function array_values. array_values ​​returns the value of the array and has nothing to do with the index. , after this processing, a new array will be formed, strictly according to the numerically increasing index, and then use the for loop to output the edges, everything will be OK!
Copy code The code is as follows:

$test_array=array(1,2,3,4,4,5,5 ,6);
$test_array_unique=array_values(array_unique($test_array));
for($i=0;$i{
echo $ test_array_unique[$i];
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/319740.htmlTechArticleFor example: Copy the code as follows: $test_array=array(1,2,3,4,4,5, 5,6); $test_array_unique=array_unique($test_array); print_r($test_array_unique); $test_array=array(1,2,3,4,4,5,5,6);...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!