PHP Variable

In PHP, a variable is a named container that holds a value, which can be a string, number, or any other data type. You can use variables to store and manipulate data throughout your code.

To create a variable in PHP, you need to use the dollar sign ($) followed by the name of the variable. Variable names in PHP must start with a letter or underscore character, followed by any combination of letters, numbers, or underscore characters. Variable names are case-sensitive, which means that $myVar and $MyVar are considered two different variables.

Here’s an example of how to create a variable and assign a value to it:

$myVar = "Hello, world!";

In this example, we have created a variable called $myVar and assigned it the string value “Hello, world!”.

You can also change the value of a variable later in your code by simply assigning a new value to it, like this:

$myVar = "Goodbye, world!";

Now, the value of $myVar has been changed to “Goodbye, world!”.

You can use variables in many different ways in your PHP code, such as concatenating strings, performing mathematical operations, or storing user input.

PHP  variable is temporary area which hold the information in php script. 

 

How are variables declared and used in PHP?

In PHP $ sign is using in front of the variable name.
Some important points to know about variables:
PHP is a loosely typed language, so no need to declare the data types of the variables which is used in PHP code . It automatically analyzes the values and stores correct data type into the variable

Example for for PHP Variable

<?php
$n=10;
$m=20;
echo “Number :$n and $m”;
?>

PHP Variable Scope

Variable scope means where it is defined and how the script can access from the code. Or the context within which it is defined. In PHP the variable scope can be local and global

<?php
$ctr = 1;
include 'test.php';
?>
  • In the above example, ctr has used
  • this ctr variable also has  used in test.php
  • Variable used in user  define function is local
<?php

$x = 1;  /* global scope */ 

function w3html()
{ 
    echo $x; /* reference to local scope variable */ 

echo " x variable has =".$x;

} 

w3html();
?>

The Global keyword

  • In the above example $x variable not displaying any output due to the scope of the variable.
  • Define global keyword in front of $x ,which is used in w3html() function.
<?php
$x = 1;  /* global scope */ 

function w3html()
{ 
    echo $x; /* reference to local scope variable */ 

echo " x variable has =".$x;

} 

w3html();
?>

Naming Rules/Convention for Variables

• PHP variable name only start with a letter or an underscore “_”

• PHP variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )

• PHP variable name should not contain spaces. For more than one word should be separated by underscore ($w3_html), or with capitalization ($w3Html)

• PHP variable $n and $N both are different .In PHP variable name is case sensitive