Variables In PHP

A PHP variable is a storage space in which any kind of information or data can be kept. Variables can be used in any PHP script. In addition, mathematical operations can be carried out via PHP variables.

PHP Variable Declaration

The dollar sign ($) is used to denote a PHP variable, and then the variable's actual name comes next. The name of a PHP variable can be anything you want it to be. When it comes to naming PHP variables, however, there are a few guidelines that must be followed.

Creating a Variable in PHP

To make a PHP variable, you would just write the name of the variable followed by a dollar sign ($).

You can also give this variable a value, which is what variables are for in PHP. To do this, you use the equal sign (=) and then the value. This is also called "declaring a variable."


<?php
$variable = "Hello CodesBright";
$x = 10;
$y = 20;
?>


You can see that we used double quotation marks to define a text type of data. It is known as "string" in the programming language.

Naming Rules of PHP Variables

Here are the rules for how to name PHP variables.

  • A variable's name is always followed by the dollar ($) sign.

  • You can only use letters, numbers, and underscores (A-Z, 0-9, and _) in a variable name.

  • A variable name can't start with a number.

  • Every variable name must start with a letter or an underscore.

It should be noted that variable names are case-sensitive, thus $name and $NAME are two distinct variables.

Scope of PHP Variables

A PHP variable may be declared anywhere you like, but you must take its scope into account.The area in which a variable could be used in your code is determined by its scope. PHP variable scopes come in three variations.

  • global

  • local

  • static

PHP global Scope

A "global variable" is a PHP variable that is created outside of a function and can only be used outside of a function.

In the PHP variable declaration, the global keyword is used to access global variables inside of functions.

PHP local Scope

PHP variables defined inside of functions have a local scope, meaning that only the function itself can access the variables.

PHP static Scope

Static PHP variables defined inside a function can only be accessed within the function. However, unlike local variables, they don't lose their values.

To define a static variable, the "static" keyword is used.

PHP case-sensitivity

Because PHP variable names are case-sensitive, $name and $NAME are distinct variables.

Case-sensitivity should always be considered while naming and using PHP variables.


<?php 
$color="blue"
echo "The sky is " . $color . "<br>";//This will work correctly. 
echo "My sky is " . $COLOR . "<br>"; This will make an error.
?> 

PHP Variables Output

To display the value of a PHP variable, echo or print commands are used.

Echo and print are different from one another in that print returns a value of 1, but echo does not.


<?php
$x = 10;
echo $x; // This will output 10
?>