1.2 Using the Ternary Operator


You want to establish a default value for a variable, but change that value if the user submits some input.

Technique

Use the ?: conditional to test the value of the user input:

 <?php // If the user has provided a first argument to the program use // that, otherwise STDIN (php://stdin) $filename = isset ($argv[1]) ? $argv[1] : "php://stdin"; $fp = @fopen ($filename, 'r')     or die ("Cannot Open $filename for reading"); while (!@feof ($fp)) {     $line = @fgets ($fp, 1024);     print $line; } @fclose ($fp); ?> 

Comments

The preceding code implementing the ternary operator is the equivalent of the following:

 <?php if (isset ($argv[1])) {     $filename = $argv[1]; } else {     $filename = "php://stdin"; } ?> 

However, PHP's ternary operator ( ?: ) greatly reduces the time it takes for programmers to write these statements. Its syntax is as follows :

 condition ? do_if_true : do_if_false; 

The use of the ternary operator is what is known as "syntactical sugar"; that is, it is a construct that is not needed, but is a nice way of beautifying code. None the less, it can be used to replace ugly if .. else code blocks and improve the readability of your code.

You can also use PHP's or construct to establish a default value:

 <?php $filename = $argv[1] or             $filename = "php://stdin"; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net