Categories
PHP

Variable Assignment, Expressions, and Operators

Variables are containers for storing information, such as numbers or text so that they can be used multiple times in the code. Variables in PHP are identified by a dollar sign ($) followed by the variable name. A variable name must begin with a letter or the underscore character and only contain alphanumeric characters and underscores. A variable name cannot contain spaces. Finally, variable names in PHP are case-sensitive.

This tutorial covers the following topics:

Define a Variable

PHP uses the = symbol as an assignment operator. The variable goes on the left of the equal sign, and the value goes on the right. Because it assigns a value, the equal sign is called the assignment operator.

$variableName = 'Assigned Value';

You can break the above example into the following parts:

  1. A dollar sign $ prefix
  2. Variable name
  3. The assignment operator (equal sign =)
  4. Assigned value
  5. Semicolon to terminate the statement

A PHP variable must be defined before it can be used. Attempting to use an undefined variable will trigger an error exception:

<?php
 //Declaring a variable
 $myWebsite;

 //Error - undefined variable
 echo $myWebiste

In PHP, you do not need to declare a variable separately before using it. Just assign value to a variable by using the assignment operator (equals sign =) to make it defined or initialized:

<?php
 //Defined variables
 $myWebsiter = 'BrainBell.com';
 $authors    = 7;

A defined variable can be used by referencing its name, for example, use the print or echo command (followed by the variable’s name) to display the value of the variable on the web page:

<?php
 $myWebsite = 'BrainBell.com';
 $authors   = 7;

 echo $myWebsite;
 //BrainBell.com

 echo 'Authors: '. $authors;
 //Authors: 7

Variable names are case-sensitive in PHP, so $Variable, $variable, $VAriable, and $VARIABLE are all different variables.

Text requires quotes

If you look closely at the PHP code block in the above example, you’ll notice that the value assigned to the second variable isn’t enclosed in quotes. It looks like this:

$authors = 7;

Then the ‘BrainBell.com’ did use quotes, like this:

$myWebsite = 'BrainBell.com';

The simple rules are as follows:

  • The text requires quotes (single or double)
  • No quotes are required for numbers, TrueFalse and Null

Assign a string value to a variable:

$var = "test string";

Concatenate two strings together to produce “test string”:

$var = "test" . " string";

Add a string to the end of another to produce “test string”:

$var = "test";
$var = $var . " string";

Here is a shortcut to adding a string to the end of another:

$var = "a";
$var .= " test";
//a test

Assign by reference

By default, PHP assigns all variables other than objects by value and not by reference. PHP has optimizations to make assignment by value faster than assigning by reference, but if you want to assign by reference you can use the & operator as follows:

$var1 = 1;
$var2 = &$var1; // assign by reference
$var2 += 3;
echo $var1; // 4

Assignment Operators

The assignment operator (equal = ) can be combined with other operators to make it easier to write certain expressions. See the following table:

OperatorExampleSame as
=$a = 2;
+=$a += 2;$a = $a + 2;
-=$a -= 2;$a = $a – 2;
/=$a /= 2;$a = $a / 2;
%=$a %= 2;$a = $a % 2;
.=$a .= $b;$a = $a . $b;
*=$a *= 2;$a = $a * 2;
List of assignment operators

These operators assign values to variables. They start with the assignment operator = and move on to +=, -=, etc.(see above table). The operator += adds the value on the right side to the variable on the left:

<?php
 $a = 2;
 $a += 1;
 echo $a; //3

 $b = 2;
 $b = $b + 1;
 echo $b; //3

Arithmetic Operators

Using an operator, you can manipulate the contents of one or more variables or constants to produce a new value. For example, this code uses the addition operator ( + ) to add the values of $x and $y together to produce a new value:

$x = 4;
$ = 7;
$z = $x + $y;

So an operator is a symbol that manipulates one or more values, usually producing a new value in the process. The following list describes the types of arithmetic operators:

OperatorDescription
+sum or addition
-subtraction
/division
*multiplication
%modulus
**exponentiation (PHP 5.6 and above)
++add 1
--subtract 1
List of arithmetic operators in PHP

Sum integers to produce an integer:

$var = 4 + 7;

The values and variables that are used with an operator are known as operands.

Subtraction, multiplication, and division might have a result that is a float or an integer, depending on the initial value of $var:

$var = (($var - 5) * 2) / 3;

Multiply to double a value:

$var = $var * 2;
$var *= 2;

Halve a value:

$var = $var / 2;
$var /= 2;

These work with float types too:

$var = 123.45 * 28.2;

Get the remainder of dividing 5 by 4:

$var = 5 % 4; //1

4 exponent (or power) of 2:

$var = 2 ** 4; //16

These all add 1 to $var:

$var = $var + 1;
$var += 1;
$var++;

And these all subtract 1 from $var:

$var = $var - 1;
$var -= 1;
$var--;

If the -- or ++ operator appears before the variable then the interpreter will first evaluate it and then return the changed variable:

$var = 1;
echo ++$var; //2
echo $var;   //2

echo --$var; //1
echo $var;   //1

If the -- or ++ operator appears after the variable then the interpreter will return the variable as it was before the statement run and then increment the variable:

$var = 1;
echo $var++; //1
echo $var;   //2

echo $var--; //2
echo $var;   //1

There are many mathematical functions available in the math library of PHP for more complex tasks. We introduce some of these in the next pages.

Operator precedence

The precedence of operators in an expression is similar to the precedence defined in any other language. Multiplication and division occur before subtraction and addition, and so on. However, reliance on evaluation orders leads to unreadable, confusing code. Rather than memorize the rules, we recommend you construct unambiguous expressions with parentheses because parentheses have the highest precedence in evaluation.

For example, in the following fragment $variable is assigned a value of 32 because of the precedence of multiplication over addition:

$variable = 2 + 5 * 6;
echo $variable; //32

The result is much clearer if parentheses are used:

$variable = 2 + (5 * 6);
echo $variable; //32

But the following example displays a different result because parentheses have the highest precedence in evaluation.

$variable = (2 + 5) * 6;
echo $variable; //42

Expressions

An expression in PHP is anything that evaluates a value; it is a combination of values, variables, operators, and functions that results in a value. Here are some examples of expressions:

$str  ='abcdef';
$x = 7;
$y = 4;
$z = $x + $y;
$x -$y;
$x;
4+7;
3;
true;
null;

An expression has a value and a type; for example, the expression 4 + 7 has the value 11 and the type integer, and the expression "abcdef" has the value abcdef and the type string. PHP automatically converts types when combining values in an expression. For example, the expression 4 + 7.0 contains an integer and a float; in this case, PHP considers the integer as a floating-point number, and the result is a float. The type conversions are largely straightforward; however, there are some traps, which are discussed later in this section.


Getting Started with PHP:

  1. Introducing PHP
  2. PHP Development Environment
  3. Variable Assignment, Expressions, and Operators
  4. Delimiting Strings
  5. Variable Substitution
  6. Constants