PHP Variables
In this tutorial, you will learn how to use PHP variables to store data in program.
Define a Variable
A variable can hold any type of value, such as a string, a number, an array, or an object.
A variable is given a name and is given a value. The following syntax is used to define a variable:
$variable_name = value;
The following rules must be followed when defining a variable:
- The variable name must begin with the letter $. After the dollar symbol ($), the first character must be a letter (a-z) or an underscore ( ).
- Underscores, letters, or digits can make up the remaining characters.
- Variables in PHP are case-sensitive. It means that the variables $message and $Message are completely different.
The variable $title is defined in the following example:
<?php $title = "PHP is awesome!";
The echo construct is used to display the values of variables on a webpage. Consider the following scenario:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Variables</title> </head> <body> <?php $title = 'PHP is awesome!'; ?> <h1><?php echo $title; ?></h1> </body> </html>
You’ll notice the following message if you open the page:
PHP is awesome!
Use the following syntax to show the value of a variable on a page in a more compact manner:
<?= $variable_name ?>
The value of the $title variable in the header, for example, is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Variables</title> </head> <body> <?php $title = 'PHP is awesome!'; ?> <h1><?= $title; ?></h1> </body> </html>
When PHP and HTML are mixed together, the code becomes unmaintainable, especially as the application grows. Different the code into separate files to avoid this. Consider the following scenario:
The logic for defining and assigning values to variables is stored in index.php.
- index.view.php – this file contains the code for displaying the variables.
- To include the code from index.view.php in the index.php file, use the require construct.
- The contents of the index.view.php file are as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Variables</title> </head> <body> <h1><?= $title ?></h1> </body> </html>
The contents of the index.php file are shown below:
<?php $title = 'PHP is awesome!'; require 'index.view.php';
You’ll get the same result if you open the index.php file in a web browser.
This allows you to segregate the logic code from the code responsible for displaying the file. In programming, this is referred to as the separation of concerns (SoC).