Web Programming TutorialsPHP Variables and Constants

PHP Variables and Constants

We will learn about variables, constants and echo statements in detail in this PHP variables tutorial.

  • Variables:
    • Variable in any programming language is a name given to a memory location that holds a value.
    • You can say that variables are containers for any type of values.
    • There are some rules to write variable names in PHP.
    • Rules for variable names:
      • Variable names in PHP start with a dollar ($) sign followed by the variable name.
      • Variable name can contain alphanumeric characters and underscore (_).
      • Variable names must start with a letter or an underscore (_). (For eg: $abc, $x1, $_g, $abc_1 etc.)
      • Variable names cannot start with a number.
      • Variable names are case-sensitive. (for eg: $x and $X are treated as two different variables.)
    • In PHP we don’t use any command to declare variables.
    • A variable is created as soon as you assign a value to it.
    • A variable takes a datatype according to the value assigned to it.
    • Since we don’t have to specify datatypes for PHP variables, PHP is called as loosely typed language.
    • Scope of variables:
      • Variables can be declared anywhere in the program.
      • Scope of a variable is a part of the program where the variable is accessible.
      • PHP has three different variable scopes:
        1. Local
        2. Global
        3. static
      1. Local scope:
        • A variable declared within a function has a local scope and can be accessed within a function only.
        • A function is a small program performing a particular task which is called when required.
      2. Global scope:
        • A variable declared outside a function has a global scope and can be accessed outside the function only.
        • Actually global variables can be accessed anywhere using the global keyword.
      3. Static scope:
        • A variable declared with static keyword is said to have static scope within the function.
        • Normally when variables are executed, they lose their values or memory.
        • But when a variable is declared as static, it doesn’t lose its value. It remains static within multiple function calls.
    • Variable declaration:
      • Variable is declared as follows:
      • $variable_name=value;
      • Example of variable declaration is given below:
      • $x=5;
      • $x is a variable and 5 is a value assigned to $x variable using assignment operator (=). The assignment operator assigns the right hand side value to the left hand side variable in an expression.
      • The variable name can be just alphabets or they can be some descriptive names like $school_name, $names, $games etc.
    • In PHP we can print a value of variable using an echo statement as follows:
    • <?php
      echo $x;
    • Output of this is shown below:
    • variable_output
      fig 1

    • Demonstration of Global Scope of variables:
      • Write the following code in index.php file and test it by putting it in the newly created folder var_constant in htdocs folder of xampp folder.
      • The code is as follows:
      • <?php
        $x=10; //global variable
        function myfun()
           $y=20; //local variable
           echo "Value of var x inside myfun = ".$x;
           echo "<br>";
           echo "Value of var y inside myfun = ".$y;
           echo "<br>";
        echo "Value of var x outside myfun = ".$x;
        echo "<br>";
        echo "Value of var y outside myfun = ".$y;
      • Here, we have declared a global variable and a local variable in the function myfun().
      • Both the value of $x and $y are printed in the function myfun() as well as outside the function.
      • The function myfun() needs to be called for execution as done in the statement myfun().
      • You will get the following error shown in the figure below:
      • global_var_error_output
        fig 2

      • This error occurs because the global variable $x is not accessible in the function myfun().
      • And local variable $y of function myfun() is not accessible outside the function.
      • Now just comment the following statements given below in the code:
      • echo "Value of var x inside myfun = ".$x;
        echo "Value of var y outside myfun = ".$y;
      • We will get the following output:
      • global_var_error_free_output
        fig 3

      • But meaning of global is accessible everywhere, and here we see that the global variable $x is not accessible inside the function myfun().
      • We can make it accessible by using keyword global before the variable $x inside function myfun(). It is shown below:
      • <?php
        $x=10;  //global variable
        //echo $x;
        function myfun()
           global $x;  //accessing global variable inside function
           $y=20;  //local variable
           echo "Value of var x inside myfun = ".$x;
           echo "<br>";
           echo "Value of var y inside myfun = ".$y;
           echo "<br>";
        echo "Value of var x outside myfun = ".$x;
        echo "<br>";
        //echo "Value of var y outside myfun = ".$y;
      • In the above code we have a statement global $x; written inside the function myfun(). This allows access to global variable inside the function.
      • Now let us see the output of the above code:
      • global_var_accessible_inside_function
        fig 4

      • The statement Value of var x inside myfun = 10 proves that now the value of $x is accessible in function myfun().
      • The statement
        echo "Value of var y outside myfun = ".$y; 

        is commented in the program because it will give error since the local variables are not accessible outside the function.

      • You might have noticed a period (.) in the echo statement. For example let us see the following statement:
      • echo "Value of var y outside myfun = ".$y; 
      • Here we have a period (.) in between a string “Value of var y outside myfun = “ and variable $y. This period is used for concatenating/joining two values.
    • Demonstration of Static Scope of variables:
      • We discussed that static scope means the value of a variable is retained within multiple function calls.
      • Let us try to demonstrate it.
      • Write the following code in index.php file by commenting all the previous code:
      • <?php
        function static_eg()
        	static $y=0;
        	echo "non-static var x = $x &nbsp;&nbsp; static var y = $y <br>";
      • Here, we see that we have a function static_eg() that contains two variables viz. $x and $y.
      • $x is a simple local variable and $y is a local variable but also a static variable.
      • Both are initialized to zero.
      • After printing the values of both the variables using echo statement they are incremented each time.
      • The function static_eg() is called 4 times.
      • The output of the above code is given below:
      • static_scope_output
        fig 5

      • Here, we can see that the value of variable $x is zero (0) every time and the value of variable $y is incremented by 1 each time.
      • This is because a simple variable loses its value once it comes out of the block it is defined in, but a static variable retains its value each time.
  • Constants:
    • Constants are the variables whose values are not changed throughout the script.
    • A valid constant variable do not have a $ sign before its name.
    • It starts with a letter or an underscore (_).
    • Constants have global scope in the whole script.
    • Constants are useful in situations where same value is used in many places. For example: if we want to calculate an area and perimeter of a circle, we require the value of PI in both the cases. So we can have the value of PI defined as a constant and can use it effectively.
    • If we want to create an array of names having length 10, we can define the length 10 as a constant which will be used anywhere required. But if for some reason we decided to increase the length to 20, we can just change the value 10 to 20 in the constant definition which will be replicated everywhere.
    • Constants are declared using inbuilt define() function.
    • It takes 3 parameters,
      1. Name of the constant
      2. Value of the constant
      3. Whether the constant should be case-insensitive. Default value is false.
    • The third parameter of define() function is optional.
    • The false value of third parameter of define() function denotes that the constant name is case-sensitive and true value indicates that the constant name is case-insensitive.
    • Let us see how it is used in a program.
    • First we will see the case-sensitive constant.
      • Write the following code in index.php file:
      • <?php
               define("MESSAGE","Welcome to PHP!");
               echo MESSAGE;
      • Here, the third parameter is not given. By default it takes false value that means the constant becomes case sensitive.
      • In the above code for defining constant we have used define() function. Name of the constant is MESSAGE and value is Welcome to PHP!.
      • The value of constant is printed using echo statement.
      • The output is shown below:
      • MESSAGE_constant
        fig 6

      • If we use the constant name as message i.e. in small case as shown below:
      •        <?php
               define("MESSAGE","Welcome to PHP!");
               echo message;
      • It will give error as our constant is case sensitive. Echo statement should have message in upper case letters.
    • Constants can have any type of value.
    • Let us now see an example of case-insensitive constant.
      • Write the following code to define another constant:
      • <?php
        echo PI;
        echo “<br>”;
        echo pi;
      • Here, a constant PI is defined with value 3.14 and third parameter is given as true to make the constant case-insensitive that means it doesn’t matter whether it is written in uppercase or lowercase.
      • The output is shown below:
      • case_insensitive_constant
        fig 7

      • Thus we learned to create variables and constants.
    • We know that echo statement is used to display something on the webpage/browser. So let us know something more about it.
  • Echo statement:
    • Echo statement is used to display something on the webpage or browser.
    • Echo statement can display one or more strings.
    • Echo statement can be used with or without parenthesis ().
    • The word echo is a keyword. Keywords in PHP are not case sensitive and hence we can write it anyway. For eg: echo, Echo, EcHo etc.
    • Echo statements can be used to display strings, values of variables etc.
    • Write the following code to prove the above said sentence:
    • <?php
      echo "We are learning echo statement.";
      echo "<br>";
      echo $name;
      echo "<br>";
      echo $age;
    • Here, a sentence is displayed using echo statement.
    • A variable $name contains name Samuel and variable $age contains value 20. These are displayed using echo statements as shown below:
    • simple_echo_stmts
      fig 8

    • Displaying variables and string together in a single echo statement:
      • Let us make a single sentence out of the values stored in the variables $name and $age.
      • Write the following code below the above given code:
      • echo "<br><hr>";
        echo "$name is $age years old. He is elegible to vote.";
      • The output is shown below:
      • single_sentence_output
        fig 9

    • Concatenation of two strings:
      • Two or more strings or values in variables can be concatenated as shown below:
      • Write the following code:
      • <?php
        echo $fname.' '.$lname;
      • Here, two strings in variables $fname and $lname are concatenated with a space in between using a period (.).
      • The period is used in between the variable and the space to concatenate them together.
      • The output is shown below:
      • concatenated_statement
        fig 10

      • Similarly you can concatenate the HTML tags also in PHP echo statements.
      • For example:
      • Echo $fname.’ ’.$lname.’<br>’;
      • Two numbers can also be concatenated in the string format as shown below:
      • The echo statement is as follows:
      • <?php
        echo '10'.'10'.'<br>';
        echo $no1.$no2;
      • The output is shown below:
      • numbers_concatenated
        fig 11

    • Calculations in echo statement:
      • The final output can also be displayed by directly working out the calculation in echo statement.
      • We can perform various mathematical operations in an echo statement.
      • Let us see an example of obtaining an area of a circle of radius 5.
      • Write the following code:
      • <?php
        echo PI*$r*$r;
      • Here, we have used a constant PI with value 3.14 and a radius of 5 is stored in variable $r.
      • The area of circle is calculated directly in echo statement and the final value obtained after calculation is printed directly as the output.
      • The output is shown below:
      • area_of_circle_output
        fig 12

      • This can be made more user friendly or understandable as follows:
      • <?php
        echo "Area of circle with radius $r = ".(PI*$r*$r);
      • Here, we have just concatenated a statement to the formula of area of circle.
      • The output is shown below:
      • modified_area_of_circle_output
        fig 13

Thus we finished studying variables, constants and echo statement in detail in this PHP Variables and Constants tutorial.

Previous articlePHP Basics
Next articlePHP Data Types



Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article


More article

- Advertisement -