How to Create a variable in PHP

In this tutorial, We will learn How to Create a variable in PHP with an example. Also, will learn different types of variables that are available in PHP.

Variables in PHP behave the same as variables in most popular programming languages (C, C++, etc) do, but in PHP you don’t have to declare variables before you use them. If you don’t know what declaring is, don’t worry about it. It isn’t important!

A variable’s purpose is to store information so that it can be used later in the program. a variable starts with the $ sign, followed by the name of the variable.

Rules for PHP variables:

  • A variable must starts with the $ sign, followed by the name of the variable.
  • A variable name cannot start with a number.
  • A variable name must start with a letter or the underscore character.
  • A variable name can only contain alphanumeric, character, and underscores ( A-Z,0-9, and _ ).
  • Variable names are case sensitive, it means ( $x and $X ) are two different variables.

Create a variable in PHP

Declared A variable using $  and no need to define the data type.

Syntax – 

$variablename;

We can assign a value with = the operator to a variable.

Syntax –

$variablename = value;

Example – 

<?php
$num;
$num = 100;
$text = "Hello World";

echo "num : ".$num;
echo "<br>text : ".$text;

Output

num : 100
text : Hello World

There are different types of variables are available in PHP

Local variable in PHP

The variables that are declared within a function are called local variables for that function. This type of variable scope is only within the block. They are not accessible outside of a block.

<?php 

function addOne(){
  $num1 = 5; // Local variable
  $num2 = 10;  // Local variable
  $sum = $num1 + num3; // Local variable
  echo 'sum : '.$sum;
}

$num1, $num2, and $sum are not accessible outside the addOne(). If you try to access it then the page displays an undefined variable warning message.

Global variable in PHP

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. A global variable is defined by adding global keyword at the front of a variable.

<?php
$a = 1;
$b = 2;

  function Sum()
  {
    global $a, $b;
    $b = $a + $b;
  } 

Sum();
echo $b;
?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version.

 Static variable in PHP

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

Syntax –

static $variablename = value;

Example

<?php

function addOne(){
  static $num = 0;
  $num++;
  echo 'num : '.$num.'<br>';
}
addOne();
addOne();
addOne();

Output

num : 1
num : 2
num : 3

Be First to Comment

Leave a Reply

Your email address will not be published.