PHP - Remove duplicates with foreach?

余生颓废 提交于 2020-06-25 04:37:06

问题


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


回答1:


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.




回答2:


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

A very simple example:

$pageno = array_unique($pageno);



回答3:


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


来源:https://stackoverflow.com/questions/46525576/php-remove-duplicates-with-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!