Learn PHP in One Day and Learn It Well

Chapter 4: Constants, Variables, Data Types and Operators in PHP

Cool! We’ve come to Chapter 4. In this chapter, we are going to learn about constants and variables. In addition, we’ll talk about the data that variables store and the different operations we can perform on them.

Before we proceed, you may want to create a new PHP script called chap4.php and use it to test the examples in this chapter.

Done? Great! Let’s move on. We’ll start with constants.

4.1 Constants

Constants in PHP are similar to constants in Mathematics. Recall the number 3.14159 (rounded to 5 decimal places) we learned in Mathematics? This number is called Pi (π), and its value never changes.

Much like Pi in Mathematics, we can define our own constants in PHP and give them names for easy reference. To do that, we use a built-in function called define() . Once we define a constant, we are not allowed to change its value.

To use the define() function, we need to pass two arguments (separated by a comma) to the function – the name of the constant (passed with quotation marks) and the value.

The name of a constant is case-sensitive by default and can consist of letters, numbers, or underscores. However, it must start with a letter or an underscore. It is a convention to use all uppercase when naming constants.

Let’s look at an example.

define("BASIC_MEMBER", 1112020);
echo '<BR>';
define("BASIC_MEMBER", 16932);

Here, we define a constant called BASIC_MEMBER and specify its value as 1112020 . Next, we reference it using its name and use an echo statement to echo its value.

After echoing its value, we try to redefine BASIC_MEMBER and change its value to 16932 . Finally, we echo its value again. If you run the code above, you’ll get the following output:

1112020Notice: Constant BASIC_MEMBER already defined in ...1112020

If you study the output carefully, you’ll see that we did not manage to change the value of BASIC_MEMBER after defining it the first time. Hence, its value remains as 1112020 when we echo it a second time. Got it? Good!

In the example above, note that we did not enclose BASIC_MEMBER in quotation marks when we echo its value. If we use quotation marks (e.g., echo 'BASIC_MEMBER'; ), we’ll get BASIC_MEMBER as the output instead, which is not what we want. We enclose the names of constants in quotation marks only when we define them (i.e., when we call the define() function).

4.2 Variables

Next, let’s move on to variables.

Variables are used to store data in our programs. They have names, and their values can be changed when necessary.

Like constants, the names of variables need to follow certain naming rules.

Firstly, a variable name must start with the $ symbol. After this symbol, the name cannot start with a number and can only contain alpha-numeric characters and underscores ( A-z0-9 , and _ ).

Names like $userName$age1 and $user_email are fine while names like $4ever (starts with a number), $unit+NY (includes the + sign) and $var 1 (includes a space) are not.

Next, variable names are case sensitive; $userName is not the same as $username .

Finally, variable names should be meaningful. Using variables like $x$y and $z to store the name, age and password of your user will make your code confusing and less intuitive. While not mandatory, you should definitely use more meaningful names such as $name$age and $password to make your code more readable.

There are two commonly used styles when naming a variable in PHP. We can use either camel case or underscores. Camel case is the practice of writing compound words in mixed case, beginning each word (except the first) with an uppercase (e.g., $thisIsAVariable ). Another common style is to use underscores (_) to separate the words (e.g., $this_is_a_variable ).

Choosing one style over the other is a matter of personal preference. What is more important is to be consistent throughout your code. In this book, we’ll be using camelCase for variables.

To declare a variable in PHP, we write something like:

$x = 7;

Here, we declare a variable called $x and give it the value 7 . Giving a value to a variable is known as assigning a value to it.

Assigning an initial value to a variable when declaring it is known as initializing the variable. This is not mandatory in PHP. However, it is considered bad practice not to do so as it can lead to unexpected behavior in the script.

When we declare and initialize a variable, PHP allocates a certain area on the server’s storage space to store this data. You can subsequently access and modify the data by referring to it by its name. For instance, to display the value of $x , we write

echo $x;

This gives us 7 as the output. If we want to change the value of $x , we simply assign a new value to it. For instance,

$x = 5;
echo $x;

updates the value of $x and gives us 5 as the new output.

In the examples above, note that we did not enclose $x in quotation marks when we use the echo statement.

In general, we do not enclose the names of constants, variables or functions in quotation marks when we use the echo statement. This is because the echo statement treats anything enclosed in quotation marks as text or HTML code and echoes it literally. For instance, if we write echo '$x'; we’ll get $x as the output. The only exception is when it comes to variable names enclosed in double quotation marks.

If we enclose a variable name in double quotation marks, the echo statement does not echo the variable name literally. Instead, it replaces the name with the value of that variable and echoes the value. For instance, if we write

echo 'The value is $x.';
echo '<BR>';
echo "The value is $x.";

we’ll get

The value is $x.
The value is 5.

as the output. When we use single quotation marks, the echo statement outputs the text literally. In contrast, when we use double quotation marks, it replaces $x with its value. Got it?

4.3 Basic Data Types in PHP

Next, let’s talk about data types in PHP.

Variables in PHP can be used to store different types of data. The type of data a variable stores is known as its data type. In this section, we’ll discuss three basic data types – intfloat and bool .


 int refers to integers, which are numbers with no decimal parts (such as -504 and 7 ).

This data type has an upper and lower boundary, both of which are platform-dependent. In other words, it can only store numbers within a certain range. Integers that exceed these bounds (i.e., very large or very small numbers) will be interpreted as floats.


 float refers to floating-point numbers, which are numbers with decimal parts or numbers in exponential form.

Examples include 5.79-3.56 and 7E11 (i.e., 7×1011).


 bool refers to boolean and is a special data type that can only store one of two values – true or false .

These two values are not case-sensitive. In other words, trueTRUE and True all refer to the same value. Similarly, falseFALSE and False refer to the same value.

The bool data type may seem redundant at the moment. Its significance will be apparent when we discuss comparison operators and condition statements in Chapter 6.

PHP is considered to be a loosely typed language. When we declare a variable, we do not need to state its data type.

To declare a variable that stores integers, we simply assign an integer to it. To declare one that stores floats or booleans, we assign a float or boolean to it respectively.

If we have the following variables

$x = 5;
$y = 2.1;
$z = true;

 $x is an integer, $y is a float, and $z is a boolean.

To verify the data type of a variable, we can use a built-in function called var_dump() . This function requires us to provide the variable name and gives us the data type and value of the variable. The following statements


give us int(5) float(2.1) bool(true) as the output.

4.4 Type Casting

In the previous section, we learned about three basic data types in PHP – intfloat and bool . We can easily convert one data type to another. This is known as type casting.

To cast a value/variable to an integer, we add (int) or (integer) in front of the original value/variable.

To cast to a boolean, we add (bool) or (boolean) .

To cast to a float, we add (float) or (double) .

Let’s look at an example:

$p = (int)4.6;

Here, we declare a variable called $p and assign (int)4.6 to it. Next, we use the var_dump() function to display the data type and value of $p .

If we run the code above, we’ll get


as the output. The value of $p is 4 as PHP casts a float ( 4.6 ) to an integer by truncating the decimal part of the float.

Besides casting values or variables to integers, floats or booleans, we can also cast them to strings, arrays or objects. We do that by adding (string)(array) and (object) in front of the values respectively. We’ll discuss these advanced data types in subsequent chapters.

4.5 Operators in PHP

PHP comes with many operators that we can use with variables. Let’s discuss the assignment operator first.

4.5.1 The Assignment Operator

Previously, we learned to assign values to variables using the = sign. This sign is known as an assignment operator and is different from the equals sign we learned in Mathematics.

In PHP (and most programming languages), an assignment works from right to left. In other words, we assign the value (or variable) on the right side of the assignment operator to the variable on the left. Hence,

$x = 7;

is not the same as

7 = $x;

While both statements are acceptable in Mathematics, the second statement is not acceptable in PHP.

In the first statement, we assign 7 to $x . This is all right and will not give us any error. On the other hand, in the second statement, we assign $x to 7 (from right to left). This does not make any sense (as 7 is a constant) and will give us an error.

Always remember that assignment works from right to left.

4.5.2 Arithmetic operators

Next, let’s talk about arithmetic operators. 

These operators are for performing basic arithmetic operations. They include operators for addition ( + ), subtraction ( - ), multiplication ( * ), division ( / ), modulo ( % ) and exponentiation ( ** ).

Suppose you have

$x = 5;
$y = 2;
$x + $y //gives us 7,
$x - $y //gives us 3,
$x*$y //gives us 10,
$x/$y //gives us 2.5,

gives us 1 because the modulo operator gives us the remainder when 5 is divided by 2 , and $x**$y gives us 25 because the exponentiation operator gives us the value of 5 raised to the power of 2 .

4.5.3 Combined Assignment Operators

Besides the set of arithmetic operators mentioned above, we have a set of operators that combines arithmetic operations with assignment. Suppose you have

$x = 5;

and you want to add 3 to $x , you can do it as follows:

$x = $x + 3;

An assignment always happens from right to left. Hence, the expression on the right ( $x + 3 ) is evaluated first to give us 5+3 . This value is then assigned back to $x , which is the variable on the left. In other words, the value of $x becomes 8 .

In addition to writing

$x = $x + 3;

we can use the += operator. This operator is a shorthand that combines the assignment operator with the addition operator. If you write

$x = 5;
$x += 3;
echo $x;

you’ll get 8 as the output.

 $x += 3 simply means $x = $x + 3 .

Besides the += operator, we have the -= operator, which combines the - operator with the assignment operator. The same applies to all the arithmetic operators mentioned in the previous section.

Hence, $x -= 4 is the same as $x = $x - 4$x *= 2 is the same as $x = $x*2 , etc.

4.5.4 Increment/Decrement operators

Last but not least, let’s talk about the increment ( ++ ) and decrement ( -- ) operators. These operators increase or decrease the value of a variable by 1 and return the new value.

Let’s try some code (line numbers are added for reference).

1 $q = 3;
2 echo "<BR>$q<BR>";
3 echo ++$q;

If you run the code above, you’ll get the following output:


Line 2 uses the echo statement to output the original value of $q . Line 3 does the following:

1. Increment the value of $q by 1

2. Echo the new value of $q

Hence, we get 4 as the output.

The ++ operator is known as the increment operator. It can be placed in front of (known as pre-increment) or behind (post-increment) the variable name. Try changing line 3 above to

echo $q++;

and rerun the code, you’ll get


as the output this time. Surprised? This is because line 3 does the following now:

1. Echo the original value of $q .

2. Increment the value of $q by 1

In other words, the order of execution of the two tasks (increment and echo) is reversed. The increment is done after the echo statement is executed (hence the name post-increment). To prove that $q is indeed incremented, you can echo its value once more after line 3. You’ll get 4 as the output this time. Got it?

In addition to the increment operator, we have the decrement operator ( -- ). This operator consists of two minus signs and decreases the value of a variable by 1. It can also be used as a pre-decrement or post-decrement operator.

Pages: 1 2 3 4 5 6 7 8 9 10 11 12 13