Something Useful
Example 2-4. Example using
control structures and functions
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)
{
echo 'You are using Internet Explorer<br />';
}
?>
A sample output of this script may be:
You are using Internet Explorer<br />
Here we introduce a couple of new concepts. We have an if
statement. If you are familiar with the basic syntax used
by the C language, this should look logical to you. Otherwise,
you should probably pick up any introductory PHP book and
read the first couple of chapters, or read the Language
Reference part of the manual. You can find a list of PHP
books at http://www.php.net/books.php.
The second concept we introduced was the strpos() function
call. strpos() is a function built into PHP which searches
a string for another string. In this case we are looking
for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT']
(so-called haystack). If the needle is found inside the
haystack, the function returns the position of the needle
relative to the start of the haystack. Otherwise, it returns
FALSE. If it does not return FALSE, the if expression evaluates
to TRUE and the code within its {braces} is executed. Otherwise,
the code is not run. Feel free to create similar examples,
with if, else, and other functions such as strtoupper()
and strlen(). Each related manual page contains examples
too. If you are unsure how to use functions, you will want
to read both the manual page on how to read a function definition
and the section about PHP functions.
We can take this a step further and show how you can jump
in and out of PHP mode even in the middle of a PHP block:
|