3

I want to define the font-weight for my tr element based on a PHP variable. What am I doing wrong in this code?

<?
    $vartest = 1;
?>

<table>
  <tr style="font-weight: <? ($vartest === 1) ? echo bold : echo normal ?>">
    <td>aaaaaaa</td>
    <td>bbbbbbb</td>                                        
  </tr>
</table>
1
  • 2
    Ternary operators are no replacement for if..else. You cannot issue commands after ? and :, only expressions that return a value. So it has to be echo ($vartest === 1) ? 'bold' : 'normal'. Commented Sep 3, 2015 at 6:29

5 Answers 5

4

Try this :

<?php

    $vartest = 1;
?>

<table>
  <tr style="font-weight: <?php echo ($vartest === 1) ? 'bold' : 'normal' ?>">
    <td>aaaaaaa</td>
    <td>bbbbbbb</td>                                        
  </tr>
</table>
Sign up to request clarification or add additional context in comments.

4 Comments

What output you are getting and what is your expected output?
I'm getting my row not in bold but it should be in bold because $vartest is equal 1.
Check the HTML source, it is possible that PHP is echoing properly but you are not able to see the boldness due to some other reason
<?php echo can be replaced with <?= =)
3

The ternary expression is wrong. Try with -

<tr style="font-weight: <? echo ($vartest === 1) ? 'bold' : 'normal'; ?>">

1 Comment

Ok I was doing wrong your solution worked for me now. Thanks.
0

Add "" for String in your syntax.

<tr style="font-weight: <? echo ($vartest === 1) ?  "bold" :  "normal" ?>">

Comments

0

Maybe you can do it like this, using css to make it pre-defined:

<?php
$Class = "bold";
?>
<html>
<head>
    <style>
        tr.bold{
            font-weight: bold;
        }

        tr.normal{
            font-weight: normal;
        }
    </style>
</head>

<body>
    <table>
        <tr class="<?php echo $Class; ?>">
            <td>abc</td>
            <td>def</td>
        </tr>
    </table>
</body>

Comments

0

Try the below

<table>
<?php 
$result=($vartest === 1)?"<tr style='font-weight:bold'>":"<tr style='font-weight:normal'>";
    echo $result; ?>
        <td>aaaaaaa</td>
        <td>bbbbbbb</td>                                        
      </tr>
    </table>

Let me know if it is helpful

2 Comments

It didn't work, but I'm looking for a solution with ternary expression.
I have edited my answer as you wanted. Check now and let me know

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.