PHP: Displaying zero to the correct output - php

I am new to PHP and I am struggling to see why my code is not working when the echo displays 0. The code works for everything else however whenever the random operator chooses 0 it outputs 0 Negative, when I have it to display as Zero. I have no idea why it is doing this and I would appreciate any guidance.
$randomNumber = rand(-5, 5);
$var = $randomNumber;
echo $randomNumber;
echo $integerValue = (($var === 0) ? " Zero" : ($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") );

The problem is due to PHP ternary operator precedence, which works backwards compared to most other languages:
Understanding nested PHP ternary operator
Try this last line:
echo $integerValue = (($var === 0) ? " Zero" : (($var <=-1)
? " Negative" : (($var >=1)
? " Positive" : " Not Positive or Zero") ));

You are missing a parentheses:
<?php
$randomNumber = rand(-5, 5);
$var = $randomNumber;
echo $randomNumber;
echo $integerValue = (($var === 0) ? " Zero" : (($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") ) );
Explanation:
(
($var === 0) ? " Zero" : (
($var <=-1) ? " Negative" : (
($var >=1) ? " Positive" : " Not Positive or Zero"
)
)
)

You don't want to echo the assignment. You need to assign the value, then echo it. Try changing the last line to
$integerValue = (($var === 0) ? " Zero" : ($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") );
and then adding the line
echo $integerValue;

You already have another answer that explains why you weren't getting the outcome you expected, but just FYI, your multiple ternary expression can be simplified somewhat.
echo $var ? $var > 0 ? ' Positive' : ' Negative' : ' Zero';
$var will evaluate to false if it is zero so there's no need to explicitly compare it to zero, and the final "Not Positive or Zero" isn't really a possible outcome, as the result of rand will be an integer, which is either positive, negative, or zero by definition.
Parentheses aren't necessary, but they may make it more obvious what the expression is doing.
echo $var ? ($var > 0 ? ' Positive' : ' Negative') : ' Zero';

Related

Why is this shorthand if statement returning 0 when the long form works?

I have the following code where I have a value that is defined, but when I try to do any shorthand equation on it, it returns 0.
Ternary operation
$m = 1.10;
echo 'Markup Percentage : ' . ( $m > 1 ? ($m * 100) - 100 : 'N/A' ) + ' %';
Result:
Markup Percentage : 0 %
Standard operation.
$m = 1.10;
echo 'Markup Percentage : ';
if($m > 1) {
echo ($m * 100) - 100;
} else {
echo 'N/A';
}
echo ' %';
Markup Percentage : 10 %
In case it isn't obvious, the result of the Ternary operation should be the same as the standard operation. What am I doing wrong or is this a bug in php 5.4 ?
This is happening because of wrong operator. . is used for concatenation, not +. Try with -
$m = 1.10;
echo 'Markup Percentage : ' . ( ($m > 1) ? (($m * 100) - 100) : 'N/A' ) . ' %';
But I would suggest to group the operations properly when using ternary operators. Not only for ternary, for all operators. Understanding the precedence is very important.
echo 'Markup Percentage : ' . ( $m > 1 ? ($m * 100) - 100 : 'N/A' ) . ' %';
Should also work.
This is, happening because you are using multiple calculation without (, so they messed up, and another mistake is you are using + sign in place of ..
You can use ternary operator like below:
$m = 1.10;
echo 'Markup Percentage : ' . ( ($m > 1) ? (($m * 100) - 100) : 'N/A' ) . ' %';
//OP: Markup Percentage : 10 %

One line if statement in PHP

I'd like to to some thing similar to JavaScript's
var foo = true;
foo && doSometing();
but this doesn't seem to work in PHP.
I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded PHP down to a minimum for the sake of readability.
So far I've got:
<?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*</label>
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>
but even then the IDE is complaining that I have an if statement without braces.
use the ternary operator ?:
change this
<?php if ($requestVars->_name == '') echo $redText; ?>
with
<?php echo ($requestVars->_name == '') ? $redText : ''; ?>
In short
// (Condition)?(thing's to do if condition true):(thing's to do if condition false);
You can use Ternary operator logic
Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Something like this?
($var > 2 ? echo "greater" : echo "smaller")
I like to use the minimalist PHP text output syntax:
HTML stuff <?= $some_string ?> HTML stuff
(This works the same as using an <?php echo $some_string; ?>)
You can also use the ternary operator:
//(condition) ? (do_something_when_true) : (do_something_when_false);
($my_var == true) ? "It's true" : "It's false ;
Ending up like this:
<?= ($requestVars->_name=='') ? $redText : '' ?>
Sample Usage
Here are a couple more uses of ternary operators, ranging from simple to advanced:
Basic Usage:
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
Short hand Usage:
$message = 'Hello '.($user->get('first_name') ?: 'Guest');
Echo Inline
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
A bit Tougher
$score = 10;
$age = 20;
echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'
complicated level
$days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month
To learn more about ternary operators and usage, visit PHP.net Comparison Operators or here.
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true) in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
Ill provide with an other answer since the original question specifies the use of if() in html
<a class="menu-item" href="/about-us"><?= (pll_current_language() == 'en') ? 'About us' : 'Om oss' ?></a>
The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();

if statement not being respected in PHP

if ($fromcat == "true" || $fromcat == 1){
error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);
} else {
error_log("binding to ROOM " . $room . " because pfc was " . $fromcat);
}
please have a look at the code above.
I think everybody agree that if $fromcat is 0 there's no way I could get a "binding to CAT (...)" message in my console.
And yet, here it is:
[01-Apr-2013 22:34:50] binding to CAT single because pfc was 0
How is that even possible? You can't display the word CAT and the number 0 at the same time! Is PHP drunk?
Use the identical (===) comparison operator.
if ($fromcat === "true" || $fromcat === 1) {
error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);
} else {
error_log("binding to ROOM " . $room . " because pfc was " . $fromcat);
}
You are attempting to compare $fromcat to the string "true". If you wanted to compare it to the boolean true, you would use $fromcat == true. Otherwise:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
Documentation
It's also a good idea to reverse the order of your condition.
So
if ($fromcat === "true" || $fromcat === 1)
becomes
if ('true' === $fromcat || 1 === $fromcat)
Reason: PHP - reversed order in if statement

Ambiguious Ternary Statements

Working on a simple project, the objective is to find whether or not it is a leap year. In PHP, I attempted to use a ternary rather then the standard elseif statements.
$year = 2000;
$is_leapYear = ($year%400 == 0)? true: ($year%100 == 0)? false: ($year % 4 == 0);
echo ($year % 400 == 0) .'.'. ($year % 100 == 0) .'.'. ($year % 4 ==0);
echo $year . ' is ' . ($is_leapYear ? '' : 'not') . ' a leap year';
I discovered that this doesn't work because of a lack of parenthesis. Here is the correct solution:
$is_leapYear = ($year % 400 == 0)? true: (($year % 100 == 0)? false: ($year%4 == 0));
My question is why do ternary operators need parenthesis on the top true or false branch? I don't think the above code is ambiguous.
There's no need for such complicated code. PHP's date() can return whether it's a leap year or not:
$is_leap_year = (bool) date('L', mktime(0, 0, 0, 1, 1, $year));
See manual here.
There is no ambiguity and sadness of PHP Ternary Operator:
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
SOURCE
Your code executes like this:
$year = 2000;
$is_leapYear = (($year%400 == 0)? true: ($year%100 == 0)) ? false: ($year%4==0);
echo $is_leapYear;
LEFT-to-RIGHT

PHP Elseif Ternary Operators

I am trying to convert the following code into a Ternary Operator, but it is not working and I am unsure why. I think my problem is that I do not know how to express the elseif operation in ternary format. From my understanding and elseif is performed the same way as an if operation by using the format : (condition) ? 'result'.
if ($i == 0) {
$top = '<div class="active item">';
} elseif ($i % 5 == 0) {
$top = '<div class="item">';
} else {
$top = '';
}
$top = ($i == 0) ? '<div class="active item">' : ($i % 5 == 0) ? '<div class="item">' : '';
$top = ($i == 0) ? '<div class="active item">' : (($i % 5 == 0) ? '<div class="item">' : '');
you need to add parenthesis' around the entire else block
The Ternary Operator doesn't support a true if... else if... else... operation; however, you can simulate the behavior by using the following technique
var name = (variable === 1) ? 'foo' : ((variable === 2) ? 'bar' : 'baz');
I personally don't care for this as I don't find it more readable or elegant. I typically prefer the switch statement.
switch (variable) {
case 1 : name = 'foo'; break;
case 2 : name = 'bar'; break;
default : name = 'bas'; break;
}
Too late probably to share some views, but nevertheless :)
Use if - else if - else for a limited number of evaluations. Personally I prefer to use if - else if - else when number of comparisons are less than 5.
Use switch-case where number of evaluations are more. Personally I prefer switch-case where cases are more than 5.
Use ternary where a single comparison is under consideration (or a single comparison when looping), or when a if-else compare is needed inside the "case" clause of a switch structure.
Using ternary is faster when comparing while looping over a very large data set.
IMHO Its finally the developer who decides the trade off equation between code readability and performance and that in turn decides what out of, ternary vs. if else-if else vs. switch-case, can be used in any particular situation.
//Use this format before reducing the expression to one liner
$var=4; //Change value to test
echo "Format result: ";
echo($var === 1) ? 'one' : //if NB.=> $varname = || echo || print || var_dump(ternary statement inside); can only be (placed at the start/wrapping) of the statement.
(($var === 2) ? 'two' : //elseif
(($var === 3) ? 'three' : //elseif
(($var === 4) ? 'four' : //elseif
'false' //else
))); //extra tip: closing brackets = totalnumber of conditions - 1
// Then echo($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false')));
echo "<br/>";
var_dump("Short result: ", ($var === 1)?'one':(($var === 2)?'two':(($var === 3)?'three':(($var === 4)?'four':'false'))) );

Categories