Overview of This Lesson

Refresh this page because I am probably still making changes to it.

PHP syntax is very similar to that of other languages, but of course there are some small differences. We'll start to take a look at the PHP syntax in this lesson by talking about variables, constants, and the different data types that PHP has.

Resources

The following references from the PHP Manual will be helpful:

Pre-Requisites

Before doing this lesson, it's recommended that you have already gone through the Intro to PHP lesson.. It is also assumed that you're already familiar with HTML and the basics of at least one other programming language.

Basic Syntax

We already discussed PHP tags or blocks in the previous tutorial. You can review that content from the PHP Manual if you wish:

Commenting in PHP is very similar to other languages you might have already learned:

For more information about commenting in PHP, see PHP Manual: Comments.

Displaying Variables/Expressions

As you learn PHP, you're going to need to display output or display the contents of variables and results of expressions. You have several options available, depending on what you'd like to do:

The echo Statement

The echo statement displays output on the page in the location where the PHP script is.

Example:

<header>
  <h1>Demonstration</h1>
</header>

<?php 
    echo "This is some text";
    echo "<p>This is a paragraph.</p>";
<?>

<footer>
  <address>&copy; 2017 Wendi Jollymore</address>
</footer>

The browser output and the DOM output appears as:

the browser output and the Inspection window in Chrome
The browser and DOM output of the example.

Notice that the output from the first echo function is not inside any HTML element. Obviously this would be back practice, all inline content should be enclosed inside a block element, but this is just a demonstration.

The echo function can be used with or without parentheses, although note that adding parentheses just adds them to the expression itself. Ever see those people that do things like ((x * y) + 2) when you could have just written x * y + 2 ? It's the same thing: the parentheses are unnecessary and can in fact make the code less readable rather than more readable. With brackets, the code would have looked like this:

<?php 
  echo("This is some text");
  echo("<p>This is a paragraph.</p>");
 <?>

The print Statement

The print statement can also be used with or without parentheses and it is also a language construct. The print statement works exactly like echo except that print returns the integer value 1, so you can use it in expressions if needed. print also coerces non-string values into strings when they are printed. The echo statements above as print:

<?php 
    print("This is some text");  // ignoring return value
    print "<p>This is a paragraph.</p>"; // without parentheses
?>

The print statement is slightly slower than echo, so you should be using echo unless you specifically need the return value from print. Also, print can only accept a single argument, whereas echo can accept multiple arguments, although we rarely pass it more than one, anyway.

The printf Function

The printf() function works very similarly to the printf() function in the Java language: it uses format specifiers inside a format string to print formatted data. The documentation link above contains a list of the various format specifier codes (if you're familiar with the codes in Java, you'll notice there's a LOT more in PHP!) Also, unlike the Java version, printf() will return an integer representing the number of characters that will be printed.

<p>
  <?php 
      $n = 2;
      $d = 3;
      printf("%d / %d = %.2f", $n, $d, $n / $d);
  ?>
</p>

var_dump() Function

The var_dump() function is useful for testing and debugging: it displays information about the arguments you pass into it (you can pass more than one thing into var_dump(), just separate the arguments with a comma). What gets displayed depends on the argument. For example, if the argument is a variable, it will display the type and value:

<p>
  <?php 
    $foo = "bar";
    var_dump($foo);
  ?>
</p>

The above code will output

string(3) "bar"

in a paragraph element.

For arrays, you'll see each element and its index. We'll see examples of this when we learn about arrays.

Others

There are a couple of other functions you might find useful that you can explore on your own:

Identifiers and Variables

PHP follows many of the same rules for identifiers and variables that you're probably already familiar with!

Identifiers in PHP follow rules that are similar to other languages:

Variables in PHP follow the rules above, and must start with a dollar-sign $. Because PHP is weakly-typed, you don't have to explicitly declare variables in PHP, although you can using the following syntax:

$varname = defaultValue;

As you saw in the previous tutorial, you can display an expression's result using the PHP echo statement:

<?php                 
  $greeting = "Hello, World!";
  echo $greeting;
  $number = 5;
  echo $number * 5;
?>

The above example outputs:

Hello, World!25

Constants

In addition to variables, you'll probably want to use constants in your PHP code. Constants are declared using the define() function:

define("HST_RATE", .13);

The statement above defines a constant called PST_RATE with a value of .08. You use the constant in your code just like you would in any other language:

$pstTotal = HST_RATE * $subTotal;

You can also define a constant using the const keyword:

const HST_RATE = .13;

The primary difference between define() and const is that define() defines the constant at runtime and const defines the constant at compile time. This means that you can use an expression as your constant name when you use define(), and you can also define constants while the program is running:

$taxType = array("PST", "GST", "HST");
$taxRates = array(.07, .06, .13);
for ($i = 0; $i < count($taxType); $i++) {
    define($taxType[$i]."_RATE", $taxRates[$i]);  // . is the concatenation operator
}

You can't do this kind of thing with the const keyword: you can't use an expression to create the constant name (e.g. $taxType[$i]."_RATE") and you can't define a constant while the program is running (e.g. inside the loop; using const, you can only define a constant outside of any executing function).

When trying to decide which to use, remember that if your constant name is an expression or you want the constant defined at runtime, use define(), otherwise you can use const.

<?php                               
  define("GREETING", "Hello, ". $userName ."!");  // can use const, just wanted to show an example
  const MULITPLIER = 5;
  echo GREETING;
  $number = 5;
  echo $number * MULTIPLIER;
?>

Remember, you can also display the contents of a variable or expression using the echo tag:

<!doctype html>
<?php 

    const LESSON = "Variables";
?>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>PHP Syntax Demonstrations
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
      
    <body>
        <header>
            <h1>PHP Syntax Demonstrations</h1>
            <h2><?= LESSON ?></h2>
        </header>
                
        <footer>
            <address>© 2020 Wendi Jollymore</address>
        </footer>
    </body>
</html>

Data Types in PHP

Data types in PHP can be divided into three categories: scalars, compound data types, and special data types. All of these types are technically primitive types.

Scalars

Scalars contain a single piece of information (this is just a regular variable in other languages). Scalars can be bool, int, float, or string.

bool

The bool type is PHP's Boolean type and can be given a value of true or false. Alternatively, PHP supports standard "truthy" and "falsy" values. Truthy values are non-boolean values that are considered true and falsy values are non-boolean values that are considered false

Code Example

<?php 
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
                
  $isFun = True;
  $isOld = TRUE;
  $isPita = false;
  echo "<p>Is Wendi fun? $isFun<br>Is Wendi old? $isOld.<br>"
    ."Is Wendi a PITA? $isPita.</p>";
?>

This code produces the following output:

Is Wendi fun? 1
Is Wendi old? 1
Is Wendi a PITA? .

When you output a bool variable value using echo or print, or when using string interpolation, it will convert the bool value to a string value. That means a "true" value prints "1" and a "false" value prints an empty string ("").

int

The integer type int is similar to integers in other languages, as it holds any positive or negative whole number. The size of an int variable in PHP is PHP_INT_SIZE and its value is platform-specific. The minimum and maximum integer values permitted in PHP are defined by the constants PHP_INT_MIN and PHP_INT_MAX. You can read more about these three constants in the PHP Manual's Predefined Constants

In PHP 7.4 and higher, if an integer literal is large, you can use the _ underscore character to separate digits without changing the meaning of the number:

$studentIdNum = 123_456_789;

If you're interested in working with binary, hexadecimal, or octal numbers, be sure to check out the PHP Manual page for the int type - the link is in the box up above.

Note that when a bool is converted to an int, a false value is converted to 0 and a true value is converted to 1.

float

The floating point type float represents numbers with a decimal part, even if that decimal part is 0 (e.g. 5.2, -5.2, 5.0, and 0.0 are all floating point numbers. PHP floating point numbers follow the IEEE 745 standard.

Numeric literals can also be written using exponential notation:

<?php 
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
                  
    $bigNumber = 1.234e7;
	var_dump($bigNumber);
  ?>

The above code will output:

float(12340000)

Note that when you cast a float into an int, the decimal portion is removed, the value is not rounded, which is how most other languages cast floats to ints:

<?php 
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
                  
    $f1 = 8.1;
    $f2 = 8.9;
    $i1 = (int)$f1;
    $i2 = (int)$f2;
    var_dump($i1, $i2);
  ?>

The output of the above code is:

int(8) int(8)

string

The string type includes literals enclosed within "double quotes" and 'single quotes'.

As you can see in the documentation, there are a series of escape sequences you can use inside string literals, much like in other languages. For example, the sequence \n adds a newline and \\ adds a backslash. Note that the newline, when used in HTML output, only adds a newline to the source, not the actual page. To add a newline to a page, put your content inside a block element, or use a <br> tag if the use is appropriate.

String Interpolation

PHP has some neat features when it comes to printing string epxresions. For example:

<p>
  <?php 
    $n = 2;
    $d = 3;
    echo $n."/".$d." is a fraction.";
  ?>
</p>

In PHP, the dot or period ( . ) is the concatenation operator. So this echo statement concatenates the values of $n and $d with a forward slash / between them and then conatenates that to the literal " is a fraction.". The output is:

2/3 is a fraction.

The double-quotes works differently in PHP: it will parse or expand variables and some kinds of expresions. So you can write the code above as:

<p>
  <?php 
    $n = 2;
    $d = 3;
    echo "$n/$d is a fraction.";
  ?>
</p>

This code will produce the exact same output as the previous example.

You can also use some commen escape sequences like \n (newline).

If you print with single-quotes, PHP will not interpolate or parse variables and expressions, including escape sequences:

<p>
  <?php 
    $n = 2;
    $d = 3;
    echo '$n/$d is a fraction.\n';
  ?>
</p>

This code will output:

$n/$d is a fraction.\n

Knowing how PHP interpolates strings can come in handy when you want to print complex expressions. You can find more details and some additional syntax in the PHP Manual page on strings.

Compound Types

Compound data types include arrays, objects, callables, and iterables. They're called compound types because they do more than just hold a single value: they can hold many values and/or even hold functions.

Special Data Types

This category includes the special type null. It has a single value, which is null. The null value is used when you want to empty or unset a variable or resource, or initialize an object variable to an "empty" value (the equivalent of a 0 for a numeric value).

There is also a constant in PHP called NULL, which contains the value null. It can be confusing, but remember that null is a literal value and NULL is a contant name.

This also includes the type resource. The resource type is for storing references to resources such as files or databases. We'll learn about the resource type when we start learning about working with databases.

Type Conversions

Because PHP is weakly-typed, all of the following statements are valid:

<p>
    <?php 
        $myValue = "Sydney";  
        var_dump($myValue);
        $myValue = 5;
        var_dump($myValue);
        $myValue = 2.5;
        var_dump($myValue);
    ?>
</p>

The above code outputs:

string(6) "Sydney" int(5) float(2.5)

Notice that when $myValue is assigned a string, the type is string. When $myValue is assigned the integer value 5, $myValue is an int. When $myValue is assigned a floating point number 2.5, $myValue is a float.

A variable's data type is dependent on the type of its contents.

If you need to, you can explicitly cast a value into another type:

<p>
    <?php 
        $myValue = 2.5;
        var_dump($myValue);
        $myValue = (int)$myValue;
        var_dump($myValue); // outputs int(2)        
    ?>
</p>

The explicit cast operators include: (int), (float), (bool), (string), (array), and (object)

Another quick way to cast into a string is to enclose the variable in double-quotes via string interpolation:

<p>
    <?php 
      $cheese = 24;
      $cheeseString = "$cheese";
      var_dump($cheeseString);       
    ?>
</p>

The above code outputs

string(2) "24"

Practice Quiz

Try this quiz to see how well you remember what you've been learning.

  1. Read the question and choose an answer.
  2. Click the Check Answer button to check your answer.
    • If the answer is wrong, you can try a different answer.
    • Answers you've already selected are highlighted.
  3. Once you find the correct answer, or if you just want to move on, click the Next button.
  4. After the last question, you can start the quiz over if you want.

The questions and answers are randomized, so that you are encouraged to use your critical thinking skills.