2

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>

4 Answers 4

2

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 = "";

Sign up to request clarification or add additional context in comments.

Comments

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

}

5 Comments

I presume you're trying to concatenate a variable inside an echo, this isn't a problem. Your use of quotes however is creating a problem -- Keep trying
using two quotes inside one won't be an issue.
That final edit was what I was referring too. +1 to take your answer to neutral
what about this new update does fix your pb or not ?
Hi, it seems like the main problem is because I put the "if" statement out of the loop. I try to put it on the loop and it works! Thanks for your suggestion. :)
1
echo "<div class=\"firstclass $class\">This is page $page <br /></div>";

is another option

Comments

-1

Try that:

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

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.