title: Display one filename from dir per mySQL id using PHP, half way there. How to fix this?
body: <p>I will try to explain my problem as good as possible.</p>
  
  <p>These are my data:
  I have a dir (carimgs) that has a lot of images .jpg. These images are linked to ids like 1234_img8.jpg 1234_img9.jpg. The id found in he database is 1234. A query car id may have a lot of images and all ids have 4 digits.</p>
  
  <p>From the database I get a selection of ids as you can see in the code. Logically, the ids that I get from the mySQL are fewer than the listed images ids from the dir.</p>
  
  <p>So I make a comparison between the ids I got from the DB and all the images from the dir and display only those image ids that are found through the database ids.</p>
  
  <p>The code works correctly and it selects only the images that have an id from the query. However, the problem is that all images that are linked to an id are displayed, but I want only one image per id, specifically the one that is ascending alphabetically.</p>
  
  <p>For example </p>
  
  <pre><code>5667-054.jpg
  5667-055.jpg
  5667-056.jpg
  5667-057.jpg
  5667-058.jpg
  5667-059.jpg
  5667-060.jpg
  </code></pre>
  
  <p>I want the <strong>5667-054.jpg</strong></p>
  
  <p>and from </p>
  
  <pre><code>5659-DSC01703.jpg
  5659-DSC01704.jpg
  5659-DSC01705.jpg
  </code></pre>
  
  <p>the <strong>5659-DSC01703.jpg</strong></p>
  
  <p>Here is what I get instead for example:</p>
  
  <pre><code>database ids: 4814,5513,5014,5633
  images: 4814-161.jpg,5513-223.jpg,5014-008.jpg,5633-5112509_t_b.jpg ......... 4814-147.jpg,5388-099.jpg,5353-039.jpg,5351-005.jpg,5558-003.jpg
  </code></pre>
  
  <p><strong>you can see that I get all the 4814 images</strong></p>
  
  <p>Here is my code.</p>
  
  <p>How can I achieve this?</p>
  
  <pre><code>//get the car ids based on the query
  $dbid=mysql_query("SELECT id FROM cars where disabled=0 and guar=1 order by id asc");
  while($carid = mysql_fetch_assoc($dbid)) { 
  $alldbids .= $carid[id].',';
   } 
   $alldbids = substr($alldbids, 0, -1);
  
  
   $idsArray = explode(',', $alldbids);
  
  
  $hasImages = array();
  $xalloumi = array();
  
  foreach (new DirectoryIterator(__DIR__ . '/carimgs') as $fileInfo) {
      if ($fileInfo-&gt;isDot() || $fileInfo-&gt;isDir()) {
          continue;
      }
  
      foreach ($idsArray as $id) {
          if (0 === strpos($fileInfo-&gt;getBasename(), $id)) {
              $hasImages[] = $id;
              $xalloumi[] = $fileInfo-&gt;getBasename();
              break;
          }
      }
  }
  
  $hasImages = array_unique($hasImages);
  
  $xalloumi = array_unique($xalloumi);
  
   var_dump( implode( ',', $hasImages ) );
    var_dump( implode( ',', $xalloumi ) );
  </code></pre>