Need a Website Or Web Application Or Any Help In Code , Contact Us: +91 9437911966 (Whatsapp), Note: Paid Service
Students Tutorial app relased. Download Now.

PHP Variable

In PHP Variables are used for storing values such as numeric values, characters, character strings, or memory addresses.

In PHP, a variable starts with the $ sign, followed by the name of the variable.

Rules for PHP variables:

Example

<!DOCTYPE html>
<html>
<body>
<?php
$a = "www.studentstutorial.com";
echo " $a is a PHP Tutorial";
? >
</body>
</html>

Run It Yourself »

Output

www.studentstutorial.com is a PHP Tutorial

Example

<!DOCTYPE html>
<html>
<body>
<?php
$a = 20;
$b= 10;
echo $a + $b;
? >
</body>
</html>

Run It Yourself »

Output

30

Note- Variable name are user defined. You can take any name as your choice.

PHP has three different variable scopes:

Local Variable scope

A variable declared within a function is called as LOCAL SCOPE and can only be accessed within that function.

Example

<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$a = 10; // local scope
echo "<p>Variable a inside function is: $a</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable a outside function is: $a</p>";
? >
</body>
</html>

Run It Yourself »

Global Variable scope

A variable declared outside a function is called as GLOBAL SCOPE variable and can only be accessed outside a function:

Example

<!DOCTYPE html>
<html>
<body>
<?php $a = 10; // global scope
function myTest() {
// using a inside this function will generate an error
echo "<p>Variable a inside function is: $a</p>";
}
myTest();
echo "<p>Variable a outside function is: $a</p>";
? >
</html>

Run It Yourself »

Static Variable Scope

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.