Jack
Jack

Reputation: 119

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

Upvotes: 7

Views: 19385

Answers (3)

raidenace
raidenace

Reputation: 12826

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.

Upvotes: 14

stuiterveer
stuiterveer

Reputation: 95

Apart from the answers already provided, you can also use array_unique().

A very simple example:

$pageno = array_unique($pageno);

Upvotes: 2

Tom
Tom

Reputation: 11

You can create a temporary list of page numbers. Duplicate instances will then be removed from the list of $elements:

// Create a temporary list of page numbers
$temp_pageno = array();
foreach($elements as $key => $el) {
    $pageno = $el->getAttribute("pageno");
    if (in_array($pageno, $temp_pageno)) {
        // Remove duplicate instance from the list
        unset($elements[$key]);
    }
    else {
        // Ad  to temporary list
        $temp_pageno[] = $pageno;
    }

    echo  $pageno ;
}

Upvotes: 1

Related Questions