0

My code still displays the duplicate values, even after trying both functions in_array and array_unique. I get values from database. Some rows have multiple values. I want to break down those by commas and than remove duplicates. Please Help, Thanks In Advance.

<?php while ($row = mysql_fetch_array($sql)) {
   $mark=explode(',', $row['sku']);
   foreach($mark as $out) {
     if(!in_array($out, $array)){
     $array[] = $out;
     }
   }

}
$unique_array = array_unique($array, SORT_REGULAR);
natsort($unique_array);
print_r($unique_array);
?>

1 Answers1

0

Here is a sample code, which should do what you want: http://sandbox.onlinephpfunctions.com/code/4895a5b39c555835e378114eabc7ed78c6811285

<?php

// I create some sample data
$rows = [['sku' => 'a,b,c'], ['sku' => 'c,d,e'], ['sku' => 'e,f,g']];

$array = [];

// You want to replace this with your while loop
foreach ($rows as $row) {
    $mark = explode(',', $row['sku']);

    foreach ($mark as $out) {
        if (!in_array($out, $array)) {
            array_push($array, $out);
        }
    }

}

// I don't think you need this here, because you already ensure that the array won't contain duplicates
$unique_array = array_unique($array, SORT_REGULAR);

natsort($unique_array);
var_dump($unique_array);
var_dump($array);

So using your while ($row = mysql_fetch_array($sql)) it should be like:

<?php

$array = [];
while ($row = mysql_fetch_array($sql)) {
    $mark = explode(',', $row['sku']);

    foreach ($mark as $out) {
        if (!in_array($out, $array)) {
            array_push($array, $out);
        }
    }

}

natsort($unique_array);
var_dump($unique_array);
Philipp
  • 1,289
  • 1
  • 16
  • 37
  • Thank you for your help, i have tried editing my code, but doesnot works for me, can you check please while ($row = mysql_fetch_array($third)) { $nmp[] = $row['sku']; } foreach ($nmp as $row) { $mark=explode(',', $row); foreach($mark as $out) { if (!in_array($out, $array, true)) { array_push($array, $out); echo $out; } } } natsort($array); foreach ($array as $color) { echo $color.'
    '; }
    – user3180708 Mar 21 '16 at 12:41
  • Could you update the original post with your code or create a new question if the problem is different? Could you also provide an example showing your problem, e.g., using http://sandbox.onlinephpfunctions.com – Philipp Mar 21 '16 at 12:45