I have two global variables declared in my config.php file, I would like to call one of these depending on results from another page however I need some help with my syntax.
It simply add a class to the button (btn-success
or btn-default
)
config.php
define("BTN_SUCCESS", "btn-success");
define("BTN_DEFAULT", "btn-default");
I want to do something like the following but it doesn't work it simply prints out the names in my html source;
echo '<td>
<button id="fav" type="button" class="btn '.BTN_SUCCESS. || 'BTN_DEFAULT''"></button>
</td>';
If I insert either of them individually they work but it's not what I want, for example;
echo '<td>
<button id="fav" type="button" class="btn '.BTN_SUCCESS.'"></button>
</td>';
I want an or operator in there - is this possible? It's probably something simple. Quite new to php so any help is appreciated.
Try this
echo '<td>
<button id="fav" type="button" class="btn '.(BTN_SUCCESS?:BTN_DEFAULT).'"></button>
</td>';
The parenthesis is shorthand for
if(BTN_SUCCESS)
echo BTN_SUCCESS;
else
echo BTN_DEFAULT;
The if-condition above can be shortened using ternary operators:
echo BTN_SUCCESS ? BTN_SUCCESS : BTN_DEFAULT;
And if you want to echo the value of the condition (in this case BTN_SUCCESS
) if it's truthful you can shorten it even more by removing the middle part (as of PHP 5.3):
echo BTN_SUCCESS ?: BTN_DEFAULT;
You need to first set the class depending on the value, then echo the class.
<?php
$class = $somethingIsTrue ? BTN_SUCCESS : BTN_DEFAULT;
?>
echo '<td>
<button id="fav" type="button" class="btn '.$class.'"></button>
</td>';