PHP – Compare array and output found values

i have a problem trying to get some functionality to work in PHP which i am sadly not very fond of. I tried reading and wrapping my head around it but i guess i am just to unexperienced to find the correct solution myself. I was hoping that you could point me into the right direction.

The issue:

We have an image folder full of product pictures. Their naming conventions are like this :

  • EK016_9BL_P_1
  • EK016_9BL_P_2
  • EK016_9BL_P_3
  • EK016_I1T_P_1
  • EK016_I1T_P_3
  • EK022_GKC_P_1
  • EK022_GKC_P_2

and so on….

So first what i did to get a list of all the images in the folder is the following :


$dir = "C:/img";
$files = scandir($dir);
$shortcodes = [];

echo "<table>";

foreach ($files as $file){

// Trim the filename of "_-." so only the main product code remains for comparison
$trimmed= strtok($file, '_-.');

// Push cleaned filenames to a new array
array_push($shortcodes, $trimmed);

// Make each value unique so it doesn't repeat like 5x "EK016" etc
$filtered = array_unique($shortcodes);

foreach ($filtered as $shortArtCode) {
echo "</table>";


This works so far – probably not the most elegant solution but it outputs the above example list but only the main product code (everything before the _) so for example, it lists unique values like

  • EK016
  • EK018
  • EK019
  • EK022

Now that i have separated the “Main Article Code” from the file list, i want to assign the images in the folder to its respective product code, so the output would look like :

  • EK016 => EK016_9BL_P_1.jpg

  •   => EK016_9BL_P_2.jpg
  •   => EK016_9BL_P_3.jpg
  •   => EK016_9BL_P_4.jpg
  • EK018 => EK018_2BY_P_1.jpg

  •   => EK018_2BY_P_2.jpg
  •   => EK018_2BY_P_3.jpg

of course, based on the existing files in the folder that match the “Product Code”.

I have tried “in_array” comparisons, and string comparisons but with no luck since I probably need to do everything in the same loop to get proper results. Does anyone have an idea what could be done to make this quick and dirty or maybe a completely different approach I haven’t thought of?

appreciate your help 🙂