Hexana
Hexana

Reputation: 1135

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); ." > ";
    $g++; 
    } 

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.

Cheers

Upvotes: 1

Views: 475

Answers (3)

S.Mason
S.Mason

Reputation: 3647

Inside the foreach statement you need something like so:

echo "<img id='slideimg" . $g ."' class='"; 
echo ($g == 0 ) ? " showMe' " : " slide' ";
echo " src='" . htmlspecialchars($file) . "' />";

Upvotes: 1

ryantxr
ryantxr

Reputation: 4217

Sometimes it is better to break things down into steps instead of putting everything into one statement.

$files = glob('images/*.{png}', GLOB_BRACE);
$g = 0;
foreach($files as $file) { 
    if ( $g = 0 ) { 
        $classPhrase = "\"slide showMe\""; 
    } else { 
        $classPhrase = "\"slide\"";
    }
    $srcPhrase = '"' . htmlspecialchars($file) . '"';
    $id = "\"slideimg{$g}\"";
    /* Note that $classPhrase and $srcPhrase are pre-wrapped 
       in quotes because that is how the must be output. */
    echo "<img id={$id} class=". $classPhrase ." src=". $srcPhrase ." > ";
    $g++; 
} 

Upvotes: 1

Mitya
Mitya

Reputation: 34576

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 "
<img
    id='slideimg$g'
    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.

Upvotes: 2

Related Questions