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);
?>
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);