0

How can I test if the value of a PHP variable equals a number, and then change an element's css on that number.

1
  • change class of the object on this value of variable. Commented Apr 12, 2011 at 5:13

3 Answers 3

1

Considering that PHP is executed on the server, generating the page, you could use something like this :

<?php if ($variable == 10) : ?>
    <p class="firstclass">plop !</p>
<?php else : ?>
    <p class="otherclass">plop !</p>
<?php endif; ?>


Or, using the condition to only change the CSS class :

<p class="<?php echo $variable == 10 ? 'firstclass' : 'otherclass'; ?>">plop !</p>
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a name for PHP syntax like these examples? I always assumed if statements were enclosed in {} and I've never seen the second example before, ty.
That's an HTML class, not a CSS class.
@Daniel see fr2.php.net/manual/en/control-structures.alternative-syntax.php ; that alternative syntax is often used in templates, when mixing PHP and HTML.
0

I'm assuming the CSS is in a different file. You can use PHP to dynamically generate CSS. Instead of using style.css you use style.php and include the code:

<?php
header("Content-type: text/css");
?>

At the beginning of the file. This tells the user that this file is to be treated as a style sheet. This allows you to send data to the stylesheet. For instance, you use GET to to send a color code for a specific element. You use PHP on the HTML page to make a stylesheet link to style.php?color=#FFFFFF and in the stylesheet you use this:

element {
color: <?php echo $_GET["color"];?> ;
}

If this doesn't work, let me know.

Comments

0

You could use is_numeric() and a switch() statement to output the CSS number if it is inline. If your CSS is not inline, you can use separate classes and change the class.

Link - http://php.net/manual/en/function.is-numeric.php

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.