Reputation: 533
The title seems confusing but this is my first time using ternary conditions. I've read that ternary is meant to be used to make an inline if/else statement. Using no else is not possible. Is it true?
I want to change this with ternary condition for practice
if (isset($_SESSION['group']
{
if ($_SESSION['item'] == 'A')
{
echo "Right!";
}
}
It has two if statements only. The second if is nested with the other. I've also read that to make a no else possible for ternary, it just have to be set to null or empty string.
Upvotes: 2
Views: 4045
Reputation: 164
You can nest two ternary statements as this example:
echo (isset($_SESSION['group']))?($_SESSION['item']== 'A')?'Right!':null:null;
Upvotes: 1
Reputation: 5147
Did you know you can do this as well? (isset($_SESSION['group']) && ($_SESSION['item']=='A')) &&($result$c= 1);
or echo (isset($_SESSION['group']) && ($_SESSION['item']=='A')) ? 'Hello!':'World!';
Upvotes: 0
Reputation: 18354
echo (isset($_SESSION['group']) && $_SESSION['item'] == 'A') ? "Right" : ""
Better still (readable, maintainable), use:
if (isset($_SESSION['group']) && $_SESSION['item'] == 'A')
{
echo "Right!";
}
Upvotes: 5
Reputation: 12592
It's a bad example because you can use an AND-operator on the nested if:
$result = isset($_SESSION['group'] && $_SESSION['item'] == 'A' ? true : false;
Of course you can nest ternary operator, too:
$result = isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? true : false ) : false;
with echo
echo isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? "Right!" : "false" ) : "false";
Upvotes: 5
Reputation: 1791
isset($_SESSION['group'] ? (if ($_SESSION['item'] == 'A') ? echo "Right" : null) : null
Try this, I think it might work =].
For further reading on ternary conditions in Java/ whatever you're using look at http://www.devdaily.com/java/edu/pj/pj010018
Upvotes: 1