Skip to content


Tip of the Week : Nested Ternary Statement PHP

Moving complex php if statements into ternary statement syntax is not always recommended, but I think it can look quite neat and easily readable.

Ternary statements compress your code and using nested ternary statements sparingly in certain situations makes a mess of nested if statements far easier to scan when converted to a nested ternary.

e.g: If you have a matrix of 4 results depending on two boolean results you could represent this as a regular php nested if else statement:

$bTest1 = false;
$bTest2 = false;
 
	if ($bTest1) {
		if ($bTest2) {
			echo 'test 1 true, test 2 true';
		}
		else {
			echo 'test 1 true, test 2 false';
		}
	}
	else {
		if ($bTest2) {
			echo 'test 1 false, test 2 true';
		}
		else {
			echo 'test 1 false, test 2 false';
		}
	}

Or you could use a nested ternary operator syntax:

echo $bTest1
?($bTest2?'test 1 true, test 2 true':'test 1 true, test 2 false')
:($bTest2?'test 1 false, test 2 true':'test 1 false, test 2 false');

Thats the tip of the week. More tips to come next year.

Resources:
Ternary Operator Tips

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • Fark
  • Reddit
  • StumbleUpon

Profile:  Frank has been programming for the web using PHP, Javascript and numerous libraries and frameworks for the past 5 years. More articles.

Posted in Tips of the Week. Tagged with PHP, tutorial.

2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Thanks, nice tip, I’ve used that on http://www.drzz.net

  2. This should not be used as its very hard to read.
    Bad coding technique if you ask me.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.