Making multi dimensional array unique

I’m creating a multi dimensional array using this code…

$image = [];
$image[]['src'] = $row['image1'];
$image[]['src'] = $row['image2'];
$image[]['src'] = $row['image3'];
$image[]['src'] = $row['image4'];
$image[]['src'] = $row['image5'];
$image[]['src'] = $row['image6'];    
$product['images'] = $image;

The problem is sometimes image1 is the same as image2, and image2 and duplicate image6. Therefore I need to make them unique, is there anyway to use array_unique here?

I guess I could do this…

$imaget = [];
$imaget[] = $row['image1'];
$imaget[] = $row['image2'];
$imaget[] = $row['image3'];
$imaget[] = $row['image4'];
$imaget[] = $row['image5'];   
$imaget[] = $row['image6'];
$imaget = array_unique($imaget);

foreach ($imaget as $imagek) {
    $image[]['src'] = $imagek;
}

$product['images'] = $image;  

Is that the easiest way ?

How about just using array_values() instead of the foreach() loop?

http://php.net/manual/en/function.array-values.php

Scott

1 Like

Another more compact way to solve that task:

$image = []; 
$added = [];
for($i = 1; $i <= 6; $i++){
    $src = $row["image{$i}"];
    if (in_array($src, $added)){ continue; }
    $image[]['src'] = $src;
    $added[] = $src;
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.