Jack Jack - 1 year ago 163
PHP Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download