php Removes duplicate values in foreach

23,201

Solution 1

With array_unique:

foreach (array_unique($data) as $d) {
 // Do stuff with $d ...
}

Although you can technically call the array and its elements by the same name, it's bound to lead to programming errors and confusion afterwards.

Solution 2

Look what you do:

foreach ($data as $data) 

You are overwriting the contents of $data, then you access $data while you expect it still to be the original array. That's just wrong.

Take an additional variable name, pretty common is $value:

foreach ($data as $value)

Hope this helps even if it is not answering your question, but this can be part of your problem, so take care ;)

Share:
23,201
yuli chika
Author by

yuli chika

樱の花のおちるスピ--ド, 秒速5セソチメ--トル, どれほどの速さで生きれば, きみにまた会えるのか.

Updated on July 09, 2022

Comments

  • yuli chika
    yuli chika over 1 year

    I have a foreach iterator, there are 500 group items in it. How do I remove duplicate values in a foreach?

    foreach ($data as $data) {
    if(!empty($data['name'])){  //check if have $data['name']
    $name = $data['name'];
    $id = $data['id'];
    $date = $data['date'];
    $link = $data['link'];
    if(strpos($link, '.ads.')){
    continue; //remove all the link contains `.ads.`
    }else{
    // if `$link` is not repeat, echo the below data. how to use array_unique, remove all the values which repear in `$link` part? 
    echo $name;
    echo $id;
    echo $date;
    echo $link;
    } 
    }
    
    • Pekka
      Pekka almost 13 years
      Can you show an example duplicate value?
  • Asaph
    Asaph almost 13 years
    +1. Here is a link to the docs: php.net/manual/en/function.array-unique.php
  • phihag
    phihag almost 13 years
    @Asaph Beat you to it ;) Updated with a link.
  • yuli chika
    yuli chika almost 13 years
    add array_unique in foreach (array_unique($data) as $d) { there only one data return.
  • Asaph
    Asaph almost 13 years
    @yuli chika: inside the loop, use $d, not $data. Pay close attention to @phihag's advice: "Although you can technically call the array and its elements by the same name, it's bound to lead to programming errors and confusion afterwards."