7

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

7
  • It works as I'd expect, 3v4l.org/iPoZk. Perhaps $elements is not an array? getAttribute sounds like domdocument object maybe? Commented Oct 2, 2017 at 12:40
  • 1
    Why not use array_unique()? Commented Oct 2, 2017 at 13:06
  • @GrumpyCrouton he actually use array_unique in the second foreach Commented Oct 2, 2017 at 13:11
  • @MacBooc That makes even less sense to me unless it's a multi-dimensional array. In which case, just use it twice. Commented Oct 2, 2017 at 13:12
  • @GrumpyCrouton i think it's even an array of object with different values while he use getAttribute inside his loop, so array_unique can't work here imo Commented Oct 2, 2017 at 13:14

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This worked very well. Got a syntax error though. Fixed by adding a ; after 'array_push($pageNos,$pageno)'. :) Is there also a way to sort this array? It echo's: 7 6 8 1 2 3 4 5 now. I would love to have it like: 1 2 3 4 5 6 7 8.
@Jack You could probably just do PHP's sort() after the foreach and then loop through the elements afterwards again to display the page numbers.
2

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

A very simple example:

$pageno = array_unique($pageno);

Comments

1

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 ;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.