Hexana Hexana - 6 months ago 34
HTML Question

Add Conditional Image Class Name with PHP

I have 6 plain html images:

<img id="slideimg0" class="slide showMe" src="images/atmosphere.png">
<img id="slideimg1" class="slide" src="images/experts.png">
<img id="slideimg2" class="slide" src="images/pro.png">
<img id="slideimg3" class="slide" src="images/master.png">
<img id="slideimg4" class="slide" src="images/teacher.png">
<img id="slideimg5" class="slide" src="images/tuition.png">

However, I am attempting to loop through the images folder instead with PHP because the images are going to increase.

So to recreate the above with PHP I have tried:

$files = glob('images/*.{png}', GLOB_BRACE);
$g =0;
foreach($files as $file) {
echo"<img id='slideimg' " . $g ."class=". if ($g=0) { echo "slide showMe"; } else { echo "slide";} ."src=". htmlspecialchars($file); ." > ";

So what I am trying to do is when slideimg0, I want the class to equal "slide" and "showMe." The rest will just be class "slide."

I keep getting parse errors and I am not sure where the misplaced or missing single or double quotes are?

Any help appreciated.


Answer Source

All kinds of problems here. You can't concatenate a string with a control structure, like:

"class=". if ($g=0) {...

...and you're assigning (=) to $g rather than comparing against it (==).

echo "
    class='slide ".($g ? null : "showMe")."'
    src='". htmlspecialchars($file)."'

This approach uses a ternary condition, useful for conditional output in the middle of an outer expression. The alternative would have been to temporarily terminate output, enter a traditional if(...) {, then resume output afterwards.

All in all you might do well to brush up on the basics of PHP syntax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download