I have a array of page numbers:
foreach($elements as $el) {
$pageno = $el->getAttribute("pageno");
echo $pageno ;
}
Sadly it contains duplicates. I tried the follow code but it won't return a thing:
foreach(array_unique($elements) as $el) {
$pageno = $el->getAttribute("pageno");
echo $pageno ;
}
How to remove the duplicate page numbers? Thanks in advance :)
Answer: Using array_unique() function We can remove the duplicate values from the array using the PHP array_unique() function.
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
Since I do not have your data structure, I am providing a generic solution. This can be optimized if we know the structure of $elements
but the below should work for you.
$pageNos = array();
foreach($elements as $el) {
$pageno = $el->getAttribute("pageno");
if(!in_array($pageno, $pageNos))
{
echo $pageno ;
array_push($pageNos,$pageno);
}
}
Basically we are just using an additional array to store the printed values. Each time we see a new value, we print it and add it to the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With