TechniqueUse 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); ?> CommentsThe 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"; ?> |