You are looking at posts that have been tagged operator
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 votes, average: 3 out of 5)The content on this site is published under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Canada License, which allows any person to syndicate our content (modified or not) as long as this site or the content's author is attributed and the resulting work is also released under this license. Our feed is licensed slightly differently, under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.
Use of this site is subject to, and automatically constitutes acceptance of, our copyright, our licensing restrictions, our privacy policy, and our disclosure policy. Geekie.org is an asset of the FreddyWare Solutions Enterprise Network.