All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - 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:


$VariableName=value;

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

<?php

$var1="Hi India";
$var2=1234;
$var3=2.67;

?>


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

<?php
$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.


    <?php
    var1=564;
    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.


    <?php
    function hello()
    {
      var2=564;
      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.


    <?php
    function demo()
    {
      static $var1 = 0;
        echo $var1;
        $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";
      }
      else
      {
      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 ❯