2

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user874737
  • 469
  • 1
  • 9
  • 24

5 Answers5

5

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";
Nivas
  • 18,126
  • 4
  • 62
  • 76
Micromega
  • 12,486
  • 7
  • 35
  • 72
5
echo (isset($_SESSION['group']) && $_SESSION['item'] == 'A') ? "Right" : ""

Better still (readable, maintainable), use:

if (isset($_SESSION['group']) && $_SESSION['item'] == 'A')
{
   echo "Right!";
}
Nivas
  • 18,126
  • 4
  • 62
  • 76
1
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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Whitebear
  • 1,761
  • 2
  • 12
  • 22
1

You can nest two ternary statements as this example:

echo (isset($_SESSION['group']))?($_SESSION['item']== 'A')?'Right!':null:null;
Brane
  • 3,257
  • 2
  • 42
  • 53
Srinath
  • 164
  • 10
0

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

Kumar
  • 5,038
  • 7
  • 39
  • 51