PHP coding shortcut: the ternary operator

Posted on 2008.01.28
Categories: PHP; Tagged with: , , , , ,

Many of us coding or able to code in PHP often take the long route to do a simple task. Some completely “reinvent the wheel” with custom string handling functions. Others use complex while loops with simple tasks.

Most use the classic if… (then)… else… style conditional statement. Things such as the following:

<?php
if($_SERVER['REQUEST_URI']=='/index.php') {
	echo('Hello World!');
} else {
	echo('This is some other page');
}
?>

Some may have moved beyond such rudimentary coding to blocks like the following:

<?php
$request_uri = $_SERVER['REQUEST_URI'];
switch($request_uri) {
	case '/index.php':
		echo('Hello World!');
		break;
	default:
		echo('This is some other page');
}
?>

Clearly, the second takes more work. Given something as simple as echo-ing a phrase like “Hello World!” or “This is some other page”, using the switch-case syntax simply doesn’t make sense. Even the if-else syntax is a bit overkill.

That’s why programmers and coders who perform simple tasks should use the ternary operator (available in PHP and JavaScript):

<?php
echo ($_SERVER['REQUEST_URI']=='/index.php') ? 'Hello World!' : 'This is some other page';
?>

Simple, right? Right.

It follows the pattern of (expression 1) ? (expression 2) : (expression 3) where this statement evaluates to expression 2 if expression 1 returns TRUE and the statement will evaluate to expression 3 if expression 1 returns FALSE.

For more information, consult the PHP manual.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 3 out of 5)
Loading ... Loading ...

no comments yet.

Leave a comment

Names and email addresses are required (email addresses aren't displayed), url's are optional.

Comments may contain the following xhtml tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comments by unregistered users need approval, and all comments are subject to Akismet SPAM filtering. A valid e-mail address is required but will not be published or used for third-party solicitation (see our Privacy Policy). Please provide either your real name or a nickname representative of yourself.