All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

PHP Variables

PHP Variables is used to hold different types of data in the webpage.

Variable Syntax:


Code Explanation

  • $ is used to specify that this is a PHP variable.
  • VariableName is the name of the variable.
  • = is used to set the value of a variable.
  • value is used the value you can store in the variable you can store any type of value like integer, double, string, float etc.

Example of PHP Variable


$var1="Hi India";


Output of the PHP Data

You can out display PHP variable, statements etc easily with the help of echo and print methods.

Example of echo and print

$var1="This is PHP";

echo "Hello PHP";
echo "value of var1 is ".$var1;

print "Hello PHP";
print "value of var1 is ".$var1;

Code Explanation

  • Both first echo and print display Hello PHP
  • Second echo and print display the value of var1 variable with some string value of var1 is This is PHP.

Scope of PHP Variables

PHP has three different types of scope

  • Global
  • Local
  • Static

  • Global Variable

    If a variable is declared outside from the function then the variable is called Global variable.They can be accesible from anywhere in the webpage.

    echo $var1;

    Local Variable

    If a variable is declared inside in the function then the variable is called Local variable.They are accesible only inside that function.

    function hello()
      echo $var2;

    So if you can display $var2 outside from the hello function nothing will display.

    Static Variable

    Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want to preserve a local variable NOT to be deleted thats why we use static variables.

    function demo()
      static $var1 = 0;
        echo $var1;

    So if you can display $var2 outside from the hello function nothing will display.

    PHP Data Types

    PHP uses many types of data types it has total 8 kind of data types.

    • Integers: are whole numbers, without a decimal point, like 527.
    • $var1=673;

    • Doubles: are floating-point numbers, like 2.34 or 4647.3465.
    • $var1=3.3387;

    • Booleans: it has only two possible values either true or false.
    • if(true)
      echo "It is true";
      echo "It is false";

    • NULL: is a special type that only has one value: NULL.
    • $var1=NULL;

    • Strings: are group of characters, like 'PHP supports string operations.'
    • $var1="Hello PHP";

    • Arrays: are named and indexed collections of other values.
    • You will get more knowledge of array in PHP Array Chapter

      ❮ PrevNext ❯