2

I have an array like this

$array = array('Autobus', 'Ecole', 'Hopital' ...);

And this is how I echo images that are in that array

foreach ($array as $prox){
    if ($prox == 'Autobus'){
        echo '<img src="./imgs/icones/autobus.png" width="35" height="35" alt="'.$prox.'" title="'.$prox.'"/>';
    }
    if ($prox == 'Ecole'){
        echo '<img src="./imgs/icones/ecole.png" width="35" height="35" alt="'.$prox.'" title="'.$prox.'"/>';
    }
    if ($prox == 'Hopital'){
        echo '<img src="./imgs/icones/hopital.png" width="35" height="35" alt="'.$prox.'" title="'.$prox.'"/>';
    }
...

Is there any way shorter than that code to do the same thing ?

Thanks

1

5 Answers 5

5
foreach ($array as $prox){
    echo '<img src="./imgs/icones/' . strtolower($prox) . '.png" width="35" height="35" alt="'.$prox.'" title="'.$prox.'"/>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have some images name that are not == as the item in the array but when I think about it, why I don't rename those :D. Thanks
0
$array = array('Autobus', 'Ecole', 'Hopital');
foreach($array as $prox) {
   echo '<img src="./imgs/icones/'.strtolower($prox).'.png" width="35" height="35" alt="'.$prox.'" title="'.$prox.'"/>';
}

1 Comment

Ha! Let's play who can type the fastest! I wasn't even on the page a minute, some of those answers should have been up when I came in. ;)
0
foreach ($array as $prox){
$img = strtolower ($prox);
echo '<img src="./imgs/icones/'.$img.'autobus.png" width="35" height="35" alt="'.$prox.'" title="'.$prox.'"/>';    
}

Comments

0
foreach ($array as $prox){
    sprintf('<img src="./imgs/icones/%s.png" width="35" height="35" alt="%s" title="%s"/>'
            , strtolower($prox)
            , $prox
            , $prox);
}

This only works if the image name is the same (but lowercase) as $prox

2 Comments

Personal opinion: sprintf() is overkill for for any kind of simple variable insertion, and again in my opinion ruins the readability of code (I used to use it religiously, now I don't).
Personal opinion: sprintf() is fine for for this kind of simple variable insertion, and again in my opinion can help the readability of code (I sometimes use it, now and then).
0

How about something like this?

The above posters did it how I was originally going to do it, but what if you have a word like "Chemin de fer"?

At least I think that's French...

$aArray = array
(
    "autobus" => "Autobus",
    "ecole" => "Ecole",
    "hopital" => "Hopital",
);

foreach($aArray as $sImageName => $sTitle)
{
    echo '<img src="/imgs/icones/'.$sImageName.'.png" width="35" height="35" title="'.$sTitle.'" />';
}

Tadaa?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.