2

I'm working on an image gallery with portraits where I extract text from Exif data. When I edit the images I am writing the names of the people which I later show in my image gallery as captions.

I would like to make a list, but can't figure out how to make it into an array from which I can exclude duplicates with array_unique().

My code is:

$imgdir = 'images/'; //pick your folder ie.: 'images/'
$current_folder = basename(dirname(__FILE__));
$allowed_types = array('png','jpg','jpeg','gif');

$dimg = opendir($imgdir);
while($imgfile = readdir($dimg)){
    if(in_array(strtolower(substr($imgfile,-3)),$allowed_types)){
        $a_img[] = $imgfile;
        sort($a_img);
        reset ($a_img);
    }
}
$totimg = count($a_img);

?><!DOCTYPE html>
<html>
<head>
    <title>Names listing</title>
</head>
<body>
<?php
for ($x=0; $x < $totimg; $x++){
    if ($x == ($totimg-1))
        $_content = (exif_read_data('images/'.$a_img[$x])[ImageDescription]).'';
    else
        $_content = (exif_read_data('images/'.$a_img[$x])[ImageDescription]).', ';
    $_unique = $_content;
    echo $_unique;
}    
?>
</body>
</html>

If I have multiple images with the same person I get a list like:

John, John, Jane, Jane, Jane, ... etc.

What I would like is:

John, Jane, ... etc.

Thanks in advance.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
kdt2017
  • 23
  • 3

1 Answers1

0

You should store all of the ImageDescription values in a temporary array (e.g. $descriptions), then after the loop finishes call array_unique() on the temporary array to remove duplicates, then you can optionally alphabetize the values, and finally convert the remaining values to a string using implode() with [comma and space] delimiting the values.

for($x=0; $x<$totimg; ++$x){
    $descriptions[]=exif_read_data('images/'.$a_img[$x])[ImageDescription];
}
$descriptions=array_unique($descriptions);       // remove duplicates before sorting
sort($descriptions);                             // sort alphabetically
echo implode(', ',$descriptions);                // display csv
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • I had to add some parentheses, but thank you very much! – kdt2017 May 24 '17 at 09:41
  • @kdt2017 Yeah, sorry that was sloppy of me. I've fixed up my code now. You shouldn't need the extra parenthesis around your `exif` call. If I am wrong about that, let me know. – mickmackusa May 24 '17 at 10:30
  • It works fine, thanks. I have also tried to sort the list but with no luck. Is there a simple way to do that? – kdt2017 May 25 '17 at 21:26