Ricky Setiawan
Ricky Setiawan

Reputation: 83

Change css class using php variable

need your kind help here. So as the title suggest, I'm trying to change css classes using PHP variable. So basically I want to create a loop that echos some code. But I want the div class in the first loop to be different -- it should be hidden.

Here's the simplified code I made to make the problem clear. I don't know where the mistakes are. Please advise.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<style>
.hidden {
    visibility:hidden;
}

.visible {
    visibility:visible;
}

.firstclass {
    color:red;
}

</style>

</head>

<body>
<?php
    $case = 4;
    $page = "";
    $class = "";

    if ($page == 0) {
        $class = "hidden";
    }

    else {
        $class = "visible";
    }

    for ($page = 0; $page < $case; $page++) {
        echo "<div class = &quot; firstclass $class &quot; >This is page $page <br /></div>";
    }

?>
</body>
</html>

Upvotes: 2

Views: 5488

Answers (4)

web hobbit
web hobbit

Reputation: 501

for ( $page = 0; $page < $case; $page++ ) {    
  $class = ($page == 0) ? 'hidden' : 'visible' ;
  echo '<div class="firstclass"'. $class.'">This is page' .$page. '<br /></div>';

}

Upvotes: 2

Khrisna Gunanasurya
Khrisna Gunanasurya

Reputation: 745

You need to put the if condition in the looping

<?php
    for ( $page = 0; $page < $case; $page++ ) {
        if ($page == 0) $class = "hidden";
        else $class = "visible";

        echo "<div class='firstclass $class'>This is page $page <br /></div>";
    }
?>

Because there is a condition when $page == 0 then it will give a hidden class, so if you just put it outside the looping, then $page never get the an int value, because on the top of the condition there is $page = "";

Upvotes: 2

ierdna
ierdna

Reputation: 6293

echo "<div class=\"firstclass $class\">This is page $page <br /></div>";

is another option

Upvotes: 1

Yann
Yann

Reputation: 936

Try that:

for ($page = 0; $page < $case; $page++) {
echo ("<div class=\"" . $class . " firstclass\">This is page $page <br /></div>");
}

Upvotes: -1

Related Questions