Variables in PHP
In this tutorial, we will learn about variables in PHP. We will cover the basics of declaring and using variables, including naming conventions.
What are Variables
Variables in PHP are used to store data values that can be manipulated during program execution. PHP is a dynamically typed language, meaning the data type of a variable can change at runtime.
Naming Variables
When naming variables in PHP, follow these conventions:
- Variable names must start with a dollar sign ($) followed by a letter or underscore (_).
- Subsequent characters can include letters, digits, and underscores.
- Variable names are case-sensitive.
- Avoid using reserved keywords as variable names.
Syntax
The syntax to declare variables in PHP is:
$variableName = value;
Example 1: Variable storing Integer Value
- Declare an integer variable named
$num
. - Assign a value of 10 to the variable.
- Print the value of the variable.
PHP Program
<?php
// Declare and initialize an integer variable
$num = 10;
// Print the value of the variable
echo "The value of num is: $num\n";
?>
Output
The value of num is: 10
Example 2: Variable storing String Value
- Declare a string variable named
$name
. - Assign the value 'John' to the variable.
- Print the value of the variable.
PHP Program
<?php
// Declare and initialize a string variable
$name = 'John';
// Print the value of the variable
echo "The value of name is: $name\n";
?>
Output
The value of name is: John
Example 3: Variable storing Boolean Value
- Declare a boolean variable named
$isTrue
. - Assign the value
true
to the variable. - Print the value of the variable.
PHP Program
<?php
// Declare and initialize a boolean variable
$isTrue = true;
// Print the value of the variable
echo "The value of isTrue is: $isTrue\n";
?>
Output
The value of isTrue is: 1