Variables in PHP with Example
In this tutorial, you’ll learn about variables in PHP, which is one of the basic building blocks of any PHP program. You will understand how will you define and use within the PHP program.
A variable in PHP or any other programming languages like Java is simply a container that is used to store both numeric and non-numeric values.
In simple words, a variable is a named container which holds the data or information. Here, a named container refers to a name given to a memory location that stores the data during the runtime of the program. The scope of a variable defines its visibility.
The value that a variable stores can change during the execution of the program, hence its name is variable. It means you can update or modify the data stored in a variable as needed while the program runs.
Variables can have different data types, such as numbers, characters, strings, and other types. You will learn more about these data types in the next tutorial.
Defining and Declaring Variables in PHP
You can define variables in PHP with a dollar ($) symbol followed by the variable name. There are the following rules to define variables in PHP that you should keep in mind. They are as follows:
- All variable names must start with a dollar ($) symbol. For example: $college.
- Variable names are case sensitive, meaning that $NAME and $name are two different variables in the PHP language.
- Every variable name must begin with a letter or underscore character, optionally followed by more letters, numbers, or underscore character.
- You can only use alphabetic characters, both uppercase and lowercase, digits from 0 to 9, and the underscore (_) character.
- A variable name cannot contain common punctuation characters, such as commas, quotation marks, or periods.
- Variable names must not contain any spaces.
- If a variable name consists of more that one word, use an underscore (_) character to separate them. You can also write the variable name in the camel case instead of using underscore.
- A variable name cannot start with a numeric digit.
Valid and Invalid Variable Names
Here, we have listed some variable names that are valid in PHP.
$class_6 // Variable name can start with alphabetic characters.
$_number // Variable name can start with an underscore.
$my_number // Variable name can be separated with an underscore.
$myNumber // Variable name can be written in the camel case.
$chapter45
Following are the invalid variable names in PHP.
$5_count // Variable name cannot start with a numeric digit.
$day# // Variable name cannot contain the hash (#) symbol.
$my account // Variable name cannot have a space.
email // Variable name must start with a dollar ($) symbol.
$1stname
$first name
Assigning Values to Variables
Assigning values to variables in PHP is quite simple. You can assign the value of a variable by using the assignment operator (=) in a single line. The general syntax to set the value of a variable is as follows:
$variableName = value;
As you can see in the above syntax, on the left side of the assignment operator is a variable that will store a value. On the right side is a value, which can be a simple number, string, array, object, or a complex combination of operators, variables, and constants. Every variable in PHP starts with a dollar sign ($). For example:
$name = "Deepak";
In this example, we have declared a PHP variable and assigned it a string value ‘Deepak’. When you assign a string value to a variable in PHP, you must enclose it within either double quotes (“) or single quotes (‘). This tells PHP that the value is a string.
Here, we have given some examples of assigning values to variables of different data types.
<?php
$firstName = "John"; // Assigning a string value.
$age = 30; // Assigning an integer value.
$isMarried = false; // Assigning a boolean value.
$salary = 75000.50; // Assigning a float value.
$arrayValue = array(1, 2, 3, 4, 5); // Assigning an array.
?>
Accessing Variables in PHP
To access a variable in the program, simply call it by name and the PHP interpreter will replace it with its value during the execution of the program. For example:
<?php
// Variables declaration and initialization.
$first_name = "Deepak";
$x = 20;
// Accessing the variables.
echo $first_name;
echo $x;
?>
Output: Deepak20
Examples based on Assigning Values to PHP Variables
Let’s take some examples in which we will assign values to variables and display them on the browser.
Example 1:
<?php
// Assigning values to variables $x and $y.
$x = 10;
$y = 20;
// Displaying the values of variables.
echo $x;
echo $y;
?>
Output: 1020
In this example, there is no newline character or any other separator between the two echo statements. Therefore, the output will appear directly next to each other, resulting in 1020 being displayed on the same line.
How to Print Each Value on a New Line?
If you want each value to be printed on a separate line, you need to include a newline character (\n) or HTML line break (<br>) between them. Here’s how you can do it:
Using Newline Characters:
<?php
// Assigning values to variables $x and $y.
$x = 10;
$y = 20;
// Displaying the values of variables.
echo $x . "\n";
echo $y . "\n";
?>
Output: 10 20
Using HTML Line Breaks (for web output):
<?php
$x = 10;
$y = 20;
echo $x . "<br>";
echo $y . "<br>";
?>
Example 2:
<?php
// Assigning values to variables $x and $y.
$x = 120;
$y = 110;
// Adding the values of variables.
$z = $x + $y;
// Displaying the result.
echo "Result: " . $z;
?>
Output: Result: 230
Example 3:
<?php
$name = "John Doe";
$age = 30;
echo "Name: " . $name . "\n";
echo "Age: " . $age . "\n";
?>
Output: Name: John Doe Age: 30
In this example, we have declared two variables: $name and $age. We then assigned them string and integer values, respectively, and used the echo statement to output their values. As you will notice in the echo statement that we have used the dot (.) operator to concatenate strings. It combines two or more strings together into a single string.
“Name: ” . $name . “\n”: This concatenates the string “Name: ” with the value of the variable $name, and then adds a newline character “\n” at the end. As a result, you will get a single string “Name: John Doe”.
“Age: ” . $age . “\n”: Similarly, this concatenates the string “Age: ” with the value of the variable $age, followed by a newline character “\n”. As a result, you will get a single string “Age: 30”.
Variable Assignment
PHP allows you to assign variables from the values of other variables or expressions. Let’s understand it with the help of an example.
Example 4:
<?php
$x = 10;
$y = $x;
$z = $x + $y;
echo "Value of z: " . $z . "\n";
?>
Output: Value of z: 20
In this example, we have assigned a numeric value ’10’ to a variable named $x. Then, we have assigned the value of variable named $x to the variable named $y. After addition of values of both variables, we have assigned the result to the variable named $z.
Assign Multiple Values
In PHP, You can assign the same value to multiple variables in a single declaration. Here is a simple example.
Example 5:
<?php
// Assigning the same value to multiple variables.
$x = $y = $z = "Apple";
// Displaying the result.
echo $x . "\n";
echo $y . "\n";
echo $z;
?>
Output: Apple Apple Apple
In this example, we have assigned the value 10 to the variables named $x, $y, and $z all at once. The assignment is evaluated from right to left, so 10 is first assigned to $z, then $z is assigned to $y, and finally $y is assigned to $x.
Updating Variable Values
You can change the value of a variable at any time during the execution of the program. Here is an example.
Example 6:
<?php
$count = 1; // Initial value
$count = $count + 1; // Updating value
echo $count; // Outputs 2
?>
Output: 2
In this example, the value of $count is initially set to 1 and then updated by adding 1 to it, resulting in a new value of 2.
Declaring but Not Assigning Variable Values
It is not good practice to declare a variable and then use it before assigning a value to it. The reason is that PHP interpreter has no idea what data is actually stored in the variable unless you expressly define it. Consider the following example below.
Example 7:
<?php
$num;
echo $num;
?>
This example will cause a syntax error because when the code will execute, the interpreter does not know what value the variable will set to.
Output: Warning: Undefined variable $count in D:\xampp\htdocs\PHP_Project\index.php on line 3 PHP Warning: Undefined variable $count in D:\xampp\htdocs\PHP_Project\index.php on line 3
PHP is a Loosely Typed Language
Since PHP is a loosely typed language, meaning that you do not need to declare the data type of variables. PHP automatically determines the data type of a variable based on the value assigned to it.
This feature allows you to perform operations like adding a string to an integer without causing an error. PHP will automatically convert the string to a number when performing such operations. Let’s take an example based on it.
Example 8:
<?php
$number = 10;
$text = "5";
$result = $number + $text; // The string "5" is automatically converted to the integer 5
echo $result;
?>
Output: 15
In this example, PHP interpreter will automatically convert the string “5” to the integer 5 when performing the addition. As a result, the output is 15. This automatic type conversion is known as type juggling. However, it’s important to be mindful of such operations, as they can sometimes lead to unexpected results if the string does not represent a numeric value.
Get the Variables Type in PHP
PHP provides a var_dump() function to get the data type of a variable.
Example 9:
<?php
$number = 10;
$text = "5";
$result = $number + $text;
var_dump($number);
var_dump($text);
var_dump($result);
?>
Output: int(10) string(1) "5" int(15)
Example 10:
<?php
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
?>
Output: float(3.14) bool(true) array(3) { [0]=> int(2) [1]=> int(3) [2]=> int(56) } NULL
Data Types in PHP
PHP supports a wide range of data types available for storing and manipulating data. Variables can hold different types of data, which can change dynamically.
Common Data Types:
- Integer: Whole numbers (e.g., 10, -3)
- Float: Decimal numbers (e.g., 3.14, -0.99)
- String: A sequence of characters (e.g., “Hello, World!”)
- Boolean: Represents two states: true or false
- Array: Collection of values (e.g., [1, 2, 3])
- Object: Instance of a class
- NULL: Special type representing a variable with no value.
You will understand all these data types in the next tutorial. I hope that you will have understood the basic syntax and naming conventional rules to declare variables in PHP programming language and practiced all example programs.