Variables in PHP : Tutorial




Just like any other programming language, Variables in PHP are used store data.

All variables in PHP starts with $ - dollar sign, followed by the name of the variable.

e.g. $name, $age , $message
PHP variables are case-sensitive i.e. $name and $Name are treated as two different variables.
PHP variable names must start with either a letter or an _ (underscore).
PHP variables cannot start with a numeric value(e.g. $1apple).
PHP variables cannot contain special characters other then $ or _
PHP variables can hold strings,booleans,integers,float,objects etc.
e.g. :
$abc; //Allowed
$_abc; //Allowed
$abc11; //Allowed
$#abc; //Not allowed (only _ and $ special characters are allowed)
$11abc; //Not allowed (variable cannot start with numeric digit)

Assigning value to a PHP variable

We can assign value to a PHP variable using assignment operator(=).

e.g.
$name = "Mike";
$age = "19";
$message = "Hello there!";

<html>
<head>
 <body>
  <h1>
  <?php 
  
  $message = "Hello there!";
  echo $message; 
  echo "<br/>";
  $name = "Hello there!";
  echo $name; 
  echo "<br/>";
  $message = "Mike";
  echo $message; 
  echo "<br/>";
  $age = "19";
  echo $age; 
     
  ?>
  </h1>
 </body>
</html>
Output

Hello there! Mike 19

Reserved Variables in PHP

There are number of predefined variables available in PHP called as superglobals that will be covered later.

- $GLOBALS
- $_SERVER
- $_GET
- $_POST
- $_FILES
- $_REQUEST
- $_SESSION
- $_ENV
- $_COOKIE
- $php_errormsg
- $HTTP_RAW_POST_DATA
- $http_response_header
- $argc
- $argv