Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

PHP allows you to define strings using three methods: single quotation marks,
double quotation marks, or heredoc notation. Heredoc is not discussed in this
chapter because it is fairly rare compared to the other two methods, but single
quotation marks and double quotation marks work identically, with one minor
exception: variable substitution.


Consider the following code:


Click here to view code image
<?php
$age = 25
echo "You are ";
echo $age;
?>


This is a particularly clumsy way to print a variable as part of a string.
Fortunately, if you put a variable inside a string, PHP performs variable
substitution, replacing the variable with its value. That means you can rewrite
the code like this:


Click here to view code image
<?php
$age = 25
echo "You are $age";
?>


The output is the same. The difference between single quotation marks and
double quotation marks is that single-quoted strings do not have their
variables substituted. Here’s an example:


Click here to view code image
<?php
$age = 25
echo "You are $age";
echo 'You are $age';
?>


The first echo prints You are 25, and the second one prints You are
$age.


Operators


Now that you have data values to work with, you need some operators to use,
too. You have already used + to add variables together, but many other
operators in PHP handle arithmetic, comparison, assignment, and other
operators. Operator is just a fancy word for something that performs an
operation, such as addition or subtraction. However, operand might be new to

Free download pdf