PHP Basics | PHP Variables | Data Types | Whitespace | Heredoc | Codeislands

Basics of PHP

PHP scripts are generally saved with the file extension .php to signify their type. Whenever your web server is asked to send a file ending with .php, it first passes it to the PHP interpreter, which executes any PHP code in the script before returning a generated file to the end user. The basic unit of PHP code is called a statement, and ends with a semicolon to signify it is a complete statement. For clarity, one line of code usually contains just one statement, but you can have as many statements on one line as you want. These two examples do the same thing:
<?php
    // option 1
    print "Hello, ";
    print "world!";
    // option 2
    print "Hello, "; print "world!";
?>
PHP purists like to point out that print is technically not a function and, technically, they are correct. This is why print doesn't require brackets around the data you pass to it. Other language constructs that masquerade as functions include array, echo, include, require, return, and exit.
You can use parentheses with these constructs, and doing so is harmless:
<?php
    print("Hello!");
?>
Although on the surface, print and echo appear the same, they are not. The print construct behaves more like a function than echo because it returns a value (1). However, echo is more useful because you can pass it several parameters, like this:
<?php
    echo "This ", "is ", "a ", "test.";
?>
To do the same using print, you would need to use the concatenation operation (.) to join the strings together, rather than a comma. If you have several things to print out, as in that example, then echo is preferred for the sake of clarity.

Variables

Variables in PHP that is, things that store data begin with $ followed by a letter or an underscore, then any combination of letters, numbers, and the underscore character. This means you may not start a variable with a number. One notable exception to the general naming scheme for variables are "variable variables," which are covered in the next chapter. A list of valid and invalid variable names is shown in below table.
$myvarCorrect
$NameCorrect
$_AgeCorrect
$_ __AGE_ __Correct
$91Incorrect ; starts with a number
$1NameIncorrect ; starts with a number
$Name91Correct; numbers are fine at the end and after the first character
$_Name91Correct
$Name'sIncorrect; no symbols other than "_" are allowed, so apostrophes are bad
Variables are case-sensitive, which means that $Foo is not the same variable as $foo, $FOO, or $fOO.
Assigning variables is as simple as using the assignment operator (=) on a variable, followed by the value you want to assign. Here is a basic script showing assigning and outputting data note the semicolons used to end each statement:
<?php
    $name = "Paul";
    print "Your name is $name\n";
    $name2 = $name;
    $age = 20;
    print "Your name is $name2, and your age is $age\n";
    print 'Goodbye, $name!\n';
?>
There we set the $name variable to be the string Paul, and PHP lets us print out that variable after Your name is. Therefore, the output of the first print statement is Your name is Paul, because PHP will substitute $name for its value whenever it finds it by itself, or inside a double-quoted string (that is, one starting and ending with").
We then set $name2 to be $name, which effectively copies $name's value into $name2. $name2 is now set to Paul. We also set up the $age variable to be the number 20. Our second print statement outputs both variables at once, as again, PHP will substitute them inside the string.
However, the last print statement will not replace $name with Paul. Instead, it will print:
    Goodbye, $name!\n
The reason for this is that PHP will not perform variable substitution inside single-quoted strings, and won't even replace most escape characters (the exception being \'). In double-quoted strings, PHP will replace $name with its value; in a single-quoted string, PHP will consider $name to mean that you actually want it to output the text $name just like that.
When you want to append something to your variable while inside a string, PHP may consider the characters to be part of the variable. For example:
<?php
    $food = "grapefruit";
    print "These $foods aren't ripe yet.";
?>
While the desired output was These grapefruits aren't ripe yet, the actual output is different: because we have added the "s" to the end of the variable name, we have changed it from trying to read $food to trying to read $foods. The variable $foods does not exist, so PHP will leave the space blank and may generate an error. There are two ways to solve this:
<?php
    $food = "grapefruit";
    print "These ${food}s aren't ripe yet.";
    print "These {$food}s aren't ripe yet.";
?>
The braces, { and }, technically signal a variable variable when used inside a string, but in the example above, they are used to tell PHP where the variable ends. You don't need to use braces where characters being appended to a variable would make the variable name illegal, like this:
<?php
    $food = "grapefruit";
    print "This $food's flavour is bad.";
?>
That will work because you are not allowed to use apostrophes as part of your variable names.

Data types

Variables in PHP can be of type integer (a whole number), floating-point (usually called "float"; a fractional number), string (a set of characters), array (a group of data), object (a complex mix of data and functionality), or a resource (any external information, such as an image). The basic data types in PHP are shown in below table:
Data Type
Description
BooleanA truth value; can be either TRUE or FALSE.
IntegerA number value; can be a positive or negative whole number.
Double (or float)A floating-point number value; can be any decimal number.
StringAn alphanumeric value; can contain any number of ASCII characters.
When you assign a value to a variable, the data type of the variable is also set. PHP determines the data type automatically, based on the value you assign. We will be looking at data types in more depth later on; for now, you only need to know what variables are and how they work.

Whitespace

Spaces, tabs, and blank lines in between statements have no effect on how the code is executed. To PHP, this next script is treated like any other, regardless of the fact that some statements are on the same line, and others are separated by several line breaks:
<?php
    $name = "Paul"; print "Your name is $name\n";
    $name2 = $name; $age = 20;    print "Your name is $name2, and your age is $age\n";
    print 'Goodbye, $name!\n';
?>
You should use whitespace to separate your code into clear blocks, so that its meaning can be understood by visually inspecting the layout.


Heredoc

If you have a long string, you have to consider using heredoc syntax. Put simply, heredoc allows you to define your own string delimiter so that you can make it something other than a double or single quote. So, for example, we could use the string EOT (end of text) for our delimiter, meaning that we can use double quotes and single quotes freely within the body of the textthe string only ends when we type EOT.
It is a little more complicated than that in practice, but not muchthe string delimiter needs to be by itself on a line, in the very first column. That is, you cannot add spacing or tabs around it. Here is a working example:
<?php
$mystring = <<<EOT
    This is some PHP text.
    It is completely free
    I can use "double quotes"
    and 'single quotes',
    plus $variables too, which will
    be properly converted to their values,
    you can even type EOT, as long as it
    is not alone on a line, like this:
EOT;?>
There are several things to note about heredoc and the example above:
  • You can use anything you like; EOT is just an example.
  • You need to use <<< before the delimiter to tell PHP you want to enter heredoc mode.
  • Variable substitution is enabled, which means you need to escape dollar symbols if you don't want PHP to replace variables with their values.
  • You can use your delimiter anywhere in the text, but not in the first column of a new line.
  • At the end of the string, type the delimiter with no whitespace around it, followed by a semicolon.
Without heredoc syntax, complicated string assignments can become very messy.


Code Islands

There are many ways to open a PHP code island (to enter PHP parsing mode), and you are welcome to choose which you prefer. The recommended manner is to use <?php to enter PHP mode, and ?> to leave PHP mode, but you can also use the short tags version, <? and ?>.
The short version has one big advantage and two big disadvantages: you can output information from your script by using a special short tags hack, <?=, like this:
<?="Hello, world!" ?>
Here is the equivalent, written using the standard open and closing tags:
<?php
    print "Hello, world!";
?>
As you can see, the short tags version is more compact, if a little harder to read. However, the first downside to the short version is that it clashes with XML (and therefore XHTML), which also uses <? to open code blocks. This means that if you try to use XML and short-tagged PHP together, you will encounter problemsthis is the primary reason people recommend using the normal open and close tags. Short tags are always dangerous because they can be disabled in the PHP configuration file, php.ini, which means your scripts may not be portable.
Two other, lesser-used variants exist: <% %>, which opens and closes code blocks in the same way as Microsoft's ASP, and also <script language="php"></script>. These two often work better with visual editor programs such as Dreamweaver and FrontPage, but they are not recommended for general use because they need to be enabled to work.
You can switch into and out of PHP mode by using <?php and ?> whenever and as often as you want to.

No comments