madoreo
madoreo

Reputation: 33

PHP: Displaying zero to the correct output

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

Upvotes: 1

Views: 73

Answers (4)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

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';

Upvotes: 0

iavery
iavery

Reputation: 554

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;

Upvotes: 0

Kostas Stamos
Kostas Stamos

Reputation: 173

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

Upvotes: 4

Jonathan
Jonathan

Reputation: 6537

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"
        )
    )
)

Upvotes: 0

Related Questions