Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Remove duplicates with foreach?

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 :)

like image 312
Jack Avatar asked Oct 02 '17 12:10

Jack


People also ask

How to remove duplicate values in foreach loop in PHP?

Answer: Using array_unique() function We can remove the duplicate values from the array using the PHP array_unique() function.

How to remove duplicated values from array in PHP?

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.

How to remove duplicates in an array?

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.


1 Answers

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.

like image 141
raidenace Avatar answered Sep 18 '22 18:09

raidenace