Home > database >  Show images based on String
Show images based on String

Time:11-03

i want my code to show certain images based on a given string like "Brand1,Brand2,Brand3" I already declared the images with:

<?php
  $brandString ="Brand1,Brand2,Brand3";

 $images = [
    'Brand1' => 'Brand1.png',
    'Brand2' => 'Brand2.png',
    'Brand3' => 'Brand3.png',
    'Brand4' => 'Brand4.png'
];

Now I only want to show the images that are declared in the string. What is the best way to do this?

CodePudding user response:

Using explode, you can split the string into an array on every occurance of a comma. That way you can just run through your brand array by using foreach.

So, using your example it would look something like this:

<?php
 $brandString ="Brand1,Brand2,Brand3";
 $brandArray = explode(",", $brandString);
 $images = [
    'Brand1' => 'Brand1.png',
    'Brand2' => 'Brand2.png',
    'Brand3' => 'Brand3.png',
    'Brand4' => 'Brand4.png'
];

foreach($brandArray AS $brand) {
echo $images[$brand]; //this would print out the image names in order: Brand1.jpg, Brand2.jpg, Brand3.jpg
}


  • Related