PHP Example HTML Javascript jQuery Ajax CSS Java MORE

PHP Basics

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:

  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different 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
  • global
  • static

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.