PHP variables are fundamental to the PHP language (and for that matter, of any programming language!). There are two key points about PHP variables. First, the names of these variables start with a "$" sign. Second, we do not need to specify the type of a variable before we use it; this is because PHP is a dynamically-typed programming language and a variable is not associative with a storage type for its entire lifetime. Depending upon the context, PHP automatically determines the type of a variable.
Let us get started with a small PHP program (provided below) to demonstrate usage of variables. This program does several tasks: (a) defines two variables ($var1 and $var2), (b) computes their sum (using operator "+") and product (using operator "*"), and (c) assigns the sum and product to two newer variables ($sum and $product).
<?php $var1 = 10; $var2 = 4; $sum = $var1 + $var2; $product = $var1 * $var2; echo "Variables are: $var1 and $var2 <br>"; echo "Sum is $sum, Product is $product <br>"; ?>
To run this program, we store it in a file (let us call it, "basic.php") and load it using a browser ("http://localhost/basic.php"). The output merely prints the two variables along with their sum and the product. Here is the snapshot of the HTML page.
For the sake of readability, for other examples, we simply copy/paste the text output instead of showing the snapshot of the HTML page.
The above program shows how we can assign values to a variable: "$var1 = 10". An assignment takes the value on the right side (e.g. 10) and stores it in the variable (e.g. $var1) on the left side. For assignment, ordering is important. We must keep the variable (often referred to as lvalue) on the left and keep the value (literal or another variable holding a value) on the right. Assigning in the opposite manner ("10 = $var1"!) would be an error.
Variables store values and PHP supports several categories of their types.
In the above program, both $var1 and $var2 store integers --- an integer is a digit without any fractions (whole numbers). Besides an integer, PHP also provides a floating-point number for storing fractional numeric values. Typically, an integer requires 4 bytes of storage and a floating-point number requires 8 bytes of storage. More precisely, since PHP is written in C, the storage size of an integer or a float is dependent upon the underlying machine type.
When in doubt, we can use is_int() or is_float() functions to confirm the storage type of an integer or a float respectively. If the value is an integer, then is_int() returns 1, else it returns NULL. Likewise, if the value is a float, then is_float() returns 1, else it returns NULL.
We provide a simple example that uses these functions to confirm the variable type.
<?php $var1 = 10; $var2 = 4.23232; $is_int_var1 = is_int($var1); $is_int_var2 = is_int($var2); $is_float_var1 = is_float($var1); $is_float_var2 = is_float($var2); echo "Variables are: $var1 and $var2 <br>"; echo "For $var1, is_int(): $is_int_var1 and is_float(): $is_float_var1<br>"; echo "For $var2, is_int(): $is_int_var2 and is_float(): $is_float_var2<br>"; ?>
The output of the above program is provided below (we copy/paste the text from the browser). As expected, $var1 with value "10" is an integer type and $var2 with value "4.23232" is a float type. But, when we apply the is_int() to a float ($var2) or when we apply the is_float() to an int ($var1), PHP returns NULL.
Variables are: 10 and 4.23232 For 10, is_int(): 1 and is_float(): For 4.23232, is_int(): and is_float(): 1
In the earlier program, we saw addition and multiplication of variables. PHP supports arithmetic operations like subtraction using "-", division using "/", modulo using "%", etc.
Sometimes, when updating the value of a variable, we can use a simpler variant of these operations: "+=", "-=", "*=", "/=", and "%=". Thus, to increase $var1 by 10, we could simply write "$var1 += 10", instead of "$var1 = $var1 + 10". Similarly, to multiply $var with 10, we could simply write "$var1 *= 10", instead of "$var1 = $var1 * 10". Same rule applies to remaining operations in the above list.
PHP provides yet another set of handy operators: "++" and "--". These operators (also known as unary operators) increment and decrement an integer variable by 1 respectively. Thus, "$var1++" is same as "$var1 = $var1 + 1". Likewise, "$var1--" is same as "$var1 = $var1 -1".
Both "++" and "--" can be applied before or after the variable and accordingly, they have different meanings. When we apply the operator at the end of the variable (e.g. "var1++"), then the operation returns the variable first and increments it later. On the other hand, when we apply the operator at the start of the variable (e.g. "++$var1"), then the operation increments the variable first and then returns the incremented value. Thus, "$var2 = ++$var1" and "$var2 = $var1++" would mean different assignments to $var2.
We use a simple example program to demonstrate the usage of both update and unary operators.
<?php $var1 = 10; $var1 += 100; echo "After addition, var1 is $var1 <br>"; $var1 = 10; $var1 *= 10; echo "After multiplication, var1 is $var1 <br>"; $var1 = 10; $var1 /= 2; echo "After division, var1 is $var1 <br>"; $var1 = 10; $var1 %= 7; echo "After modulo, var1 is $var1 <br>"; $var1 = 10; $var2 = ++$var1; $var1 = 10; $var3 = $var1++; echo "var2 is $var2 and var3 is $var3 <br>"; ?>
We provide the output below. As we can see, "++$var1" increases the value of $var1 first and then assigns it to $var2. On the other hand, "$var1++" assigns the value first to $var3 and then increases the value of $var1.
After addition, var1 is 110 After multiplication, var1 is 100 After division, var1 is 5 After modulo, var1 is 3 var2 is 11 and var3 is 10
When there are several operations, it is possible that an expression containing more than two of these operations can appear ambiguous. As an example, for expression, "$var1 = 10 * 2 + 7 ;", it is not clear if we first multiply 10 by 2 and then add 7 or first add 2 to 7 and then multiply with 10.
To handle such cases, PHP maintains a precedence order for operations; this order allows PHP to decide the order for executing operations. We provide precedence of PHP operations in a descending order in the table provided below. This table contains some of the common PHP operators and it is certainly not complete.
Operator | Description |
---|---|
() | Parentheses |
++, -- | Increment and decrement |
! | not operator |
*, /, % | Multiplication, division, and modulo |
+, - | Addition and subtraction |
==, !=, === | Equality, Inequality, Strict equality |
& | Bitwise AND |
^ | Bitwise XOR |
| | Bitwise OR |
&& | Logical AND |
|| | Logical OR |
=, +=, -=, *=, /=, .=, %= | Assignments |
Now that we know the operation precedence list, let us revisit our earlier expression of "$var1 = 10 * 2 + 7;". As per the precedence list, "*" has a higher precedence over "+". So, PHP first multiples 10 and 2 (which becomes 20) and then adds 7 to the result. Thus, the value of $var1 would be 27 and not 90.
In PHP, parenthesis ("(" followed by ")") have higher precedence than the above operations and hence, where ever there is less clarity, we can simply use a pair of parenthesis to avoid ambiguity. Using parenthesis also improves readability of the code. Thus, in our earlier program, if we wish to do addition first, followed by multiplication, then we can clearly specify it as "$var1 = 10 * (2 + 7);". Else, if we intend to multiply 10 and 2 first and then add 7 to the result, then we can clearly specify it as "$var1 = (10 * 2) + 7;".
Sometimes, we need a variable such that once we assign a value to it, the value of variable should never change for the rest of the program. PHP allows us to define such "constant" variables using the "define" construct. Once a constant is defined, changing the value of this constant would lead to an error. We do not need to put a $ sign before the constants!
As a good practice, we should provide names of these constants in upper case and thus, implicitly indicate that this is not a regular variable.
We provide below a simple program that uses PHP constants. The output of this program is: "Sum is: 14, Product is: 40".
<?php define(TEN, 10); define(FOUR, 4); $sum = TEN + FOUR; $product = TEN * FOUR; echo "Sum is: $sum, Product is: $product <br>"; ?>
Before we move on to additional concepts, we provide examples of two special PHP types: arrays and strings.
When we define a PHP variable, the variable represents a single unit of data. However, sometimes, an application may need to store a series of data and its logic may need to perform a task on the entire series of data. For example, let us say a web application has a large number of users and it needs to store a unique user ID for them. Defining so many variables to store user ID for each user would simply be overwhelming! For such use-cases, PHP provides a new type called an array.
$array_simple[1] $array_simple[N-1] | | | | V V -------------------------------------------------------------- | 10 | 101 | -10.22 | .. | .. | "The" | "Social" | "Network" | -------------------------------------------------------------- ^ | | $array_simple[0] Figure: A PHP Array holding N elements
A PHP array holds a series of data. The data elements do not necessarily have to be of the same type! This flexibility is not found in many programming languages where each element of the array must be of the same data type. The above figure shows an array, $array_simple with N elements holding different values like integer, float, and string. Each array element is identified by an index. The first element has an index of 0, the second element has the next index value, 1, and the last element has an index of N-1. Using these array indexes, we can easily navigate the array.
To use an array, we can specify the name and the size of the array before we start using the array. Thus, "$array_simple[1000]" means that we define an array, $array_simple, and it can hold 1000 values. After this definition, we are all set to use the $array_simple.
However, PHP is flexible enough -- if we want, we can skip providing name and size of the array. With this flexibility, we can just start using the array as need arises and PHP would automatically keep track of the array (create one, if it does not exist!). Further, we can add elements to the array as need arises and PHP would automatically increase the size of the array.
We provide a small program below to demonstrate PHP arrays. We declare "$userid_array[5]" to say that $userid_array is an array of 5 elements. Next, we assign values to each of the elements. Once values are assigned, we use a "for" loop to print all the elements. A "for" loop traverses all the elements of the array; we will revisit the "for" loop later in this page.
<?php /* With $userid_array, we first define it and then use it */ $userid_array[5]; $userid_array[] = 1000; $userid_array[] = 1001; $userid_array[] = 1002; $userid_array[] = 1003; $userid_array[] = 1004; for ($counter=0; $counter < 5; $counter++) { echo "[i: $counter] userid: $userid_array[$counter] <br>y"; } $len_array = count($userid_array); echo "Length of userid_array: $len_array <br>"; ?>
The output (provided below) demonstrates usage of a PHP array.
[i: 0] userid: 1000 [i: 1] userid: 1001 [i: 2] userid: 1002 [i: 3] userid: 1003 [i: 4] userid: 1004 Length of userid_array: 5
PHP offers a rich set of functions to handle arrays. We will revisit PHP arrays later to learn more about them.
PHP strings are simply an array of char types. Each char type requires one byte of storage and so, a string is essentially an array of 1 byte-sized elements. PHP stores the string length as an attribute of the string object.
In the following figure, we show a PHP string, $var_string that holds a string, "The Social Network".
$var_string | | V ----------------------------------------------------------------------- | T | h | e | | S | o | c | i | a | l | | N | e | t | w | o | r | k | ----------------------------------------------------------------------- Figure: A string is an array of characters
Let us use a simple program to learn more about PHP strings. This program (provided below) defines the above string variable, $var_string and assigns "The Social Network" to it. For assignment, we place the string within double-quotes (or within single-quotes) and assign it to $var_string. After that, we use a "for" loop to iterate through the characters of the string. Since the "for" loop needs the length of the string, the program uses PHP's strlen() to find the total number of characters in the string.
<?php $var_string = "The Social Network"; $len_string = strlen($var_string); $count_string = count($var_string); echo "String length of var_string: $len_string <br>"; echo "Count of var_string: $count_string <br>"; for ($counter=0; $counter < $len_string; $counter++) { echo "[i: $counter] value: $var_string[$counter] <br>"; } ?>
We should note that functions strlen() and count() are different. Using count() for $var_string returns the number of elements in the array, which is 1. Using strlen() for $var_string returns the number of characters present in the string, which is 18.
As expected, the output of the above program prints each character of the string. And, as explained earlier, there is no NULL character at the end of the string.
String length of var_string: 18 Count of var_string: 1 [i: 0] value: T [i: 1] value: h [i: 2] value: e [i: 3] value: [i: 4] value: S [i: 5] value: o [i: 6] value: c [i: 7] value: i [i: 8] value: a [i: 9] value: l [i: 10] value: [i: 11] value: N [i: 12] value: e [i: 13] value: t [i: 14] value: w [i: 15] value: o [i: 16] value: r [i: 17] value: k
We will cover PHP strings in more detail in subsequent pages.