Question

Can anybody tell me why this doesn't work as expected?

<?php
      $merchant_string = '123-Reg|Woolovers|Roxio|Roxio|BandQ|Roxio|Roxio|Big Bathroom Shop|Roxio|Robert Dyas|Roxio|Roxio|PriceMinister UK|Cheap Suites|Kaspersky|Argos|Argos|SuperFit|PriceMinister UK|Roxio|123-Reg';      

      $merchant_array = explode('|', $merchant_string); 

      for($i = 0; $i<count($merchant_array); $i++)
      {
            $merchant_array = array_unique($merchant_array);

            echo $merchant_array[$i] . '<br />';
      }
?>

The results I get is:

Woolovers
Roxio

BandQ


Big Bathroom Shop

Robert Dyas

All I want is the duplicates gone :|

Was it helpful?

Solution

First, you should be calling it before the loop since it only needs to be filtered once.

Second, keys are preserved when you use array_unique(), so PHP is attempting to loop through no-longer-existent indices in your array, and may miss some out at the end as well because count($merchant_array) now returns a smaller value. You need to reset the keys first (using array_values()), then loop it.

  $merchant_array = array_values(array_unique($merchant_array));

  for($i = 0; $i<count($merchant_array); $i++)
  {
        echo $merchant_array[$i] . '<br />';
  }

Alternatively, use a foreach loop to skip the array_values() call:

  $merchant_array = array_unique($merchant_array);

  foreach ($merchant_array as $merchant) {
        echo $merchant . '<br />';
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top