Listing 13.7 creates a function that brings together the file-related functions we've just looked at into one script. Listing 13.7. A Function to Output the Results of Multiple File Tests
If this code were saved to the document root of your web server as filetests.php and run through your web browser, the output would look something like Figure 13.2 (provided you had a file called test.txt also in the document root). Figure 13.2. Output of filetests.php.![]() Notice that we used the ternary operator as a compact way of working with some of these tests. Let's look at one such test, found in line 7, in more detail: echo "<p>$f is ".(is_file($f) ? "" : "not ")."a file</p>"; We use the is_file() function as the left-side expression of the ternary operator. If it returns true, an empty string is returned. Otherwise, the string "not " is returned. The return value of the ternary expression is added to the string to be printed with concatenation operators. This statement could be made clearer but less compact, as follows: $is_it = is_file($f) ? "" : "not "; echo "<p>".$f." is ".$is_it." a file</p>"; We could, of course, be even clearer with an if statement, but imagine how large the function would become if we used the following: if (is_file($f)) { echo "<p>$f is a file</p>"; } else { echo "<p>$f is not a file</p>"; } Because the result of these three approaches is the same, the approach you take becomes a matter of preference. |