PHP Variable Length Argument Function

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.

The 3 dot concept is implemented for variable length argument since PHP 5.6.

Let’s see a simple example of PHP variable length argument function.

<?php  
function add(...$numbers) {  
    $sum = 0;  
    foreach ($numbers as $n) {  
        $sum += $n;  
    }  
    return $sum;  
}  
  
echo add(1, 2, 3, 4);  
?>  

Output:10

PHP Variable Scope

The scope of a variable is defined as its range in the program under which it can be accessed. In other words, “The scope of a variable is the portion of the program within which it is defined and can be accessed.”

PHP has three types of variable scopes:

  1. Local variable
  2. Global variable
  3. Static variable

Local variable

The variables that are declared within a function are called local variables for that function. These local variables have their scope only in that particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local scope.

A variable declaration outside the function with the same name is completely different from the variable declared inside the function. Let’s understand the local variables with the help of an example:

<?php  
    function local_var()  
    {  
        $num = 45;  //local variable  
        echo "Local variable declared inside the function is: ". $num;  
    }  
    local_var();  
?>  

Output:

Local variable declared inside the function is: 45
<?php  
    function mytest()  
    {  
        $lang = "PHP";  
        echo "Web development language: " .$lang;  
    }  
    mytest();  
    //using $lang (local variable) outside the function will generate an error  
    echo $lang;  
?>  

Output:

Web development language: PHP
Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28

Global variable

The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program. To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the function.

Let’s understand the global variables with the help of an example:

Example:

<?php  
    $name = "Sanaya Sharma";        //Global Variable  
    function global_var()  
    {  
        global $name;  
        echo "Variable inside the function: ". $name;  
        echo "</br>";  
    }  
    global_var();  
    echo "Variable outside the function: ". $name;  
?>  

Output:

Variable inside the function: Sanaya Sharma
Variable outside the function: Sanaya Sharma

Note: Without using the global keyword, if you try to access a global variable inside the function, it will generate an error that the variable is undefined.

Example:

<?php  
    $name = "Sanaya Sharma";        //global variable  
    function global_var()  
    {  
        echo "Variable inside the function: ". $name;  
        echo "</br>";  
    }  
    global_var();  
?>

Output:

Notice: Undefined variable: name in D:\xampp\htdocs\program\p3.php on line 6
Variable inside the function:

Using $GLOBALS instead of global

Another way to use the global variable inside the function is predefined $GLOBALS array.

Example:

<?php  
    $num1 = 5;      //global variable  
    $num2 = 13;     //global variable  
    function global_var()  
    {  
            $sum = $GLOBALS['num1'] + $GLOBALS['num2'];  
            echo "Sum of global variables is: " .$sum;  
    }  
    global_var();  
?>  

Output:

Sum of global variables is: 18

If two variables, local and global, have the same name, then the local variable has higher priority than the global variable inside the function.

Example:

<?php  
    $x = 5;  
    function mytest()  
    {  
        $x = 7;  
        echo "value of x: " .$x;  
    }  
    mytest();  
?>  

Output:

Value of x: 7

Note: local variable has higher priority than the global variable.

Static variable

It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we need to store a variable even after completion of function execution. Therefore, another important feature of variable scoping is static variable. We use the static keyword before the variable to define a variable, and this variable is called as static variable.

Static variables exist only in a local function, but it does not free its memory after the program execution leaves the scope. Understand it with the help of an example:

Example:

<?php  
    function static_var()  
    {  
        static $num1 = 3;       //static variable  
        $num2 = 6;          //Non-static variable  
        //increment in non-static variable  
        $num1++;  
        //increment in static variable  
        $num2++;  
        echo "Static: " .$num1 ."</br>";  
        echo "Non-static: " .$num2 ."</br>";  
    }  
      
//first function call  
    static_var();  
  
    //second function call  
    static_var();  
?>  

Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is why because $num1 is not a static variable, so it freed its memory after the execution of each function call.

PHP Variables

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know about variables:

  • As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to its correct datatype.
  • After declaring a variable, it can be reused throughout the code.
  • Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

  1. $variablename=value;  

Rules for declaring PHP variable:

  • A variable must start with a dollar ($) sign, followed by the variable name.
  • It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
  • A variable name must start with a letter or underscore (_) character.
  • A PHP variable name cannot contain spaces.
  • One thing to be kept in mind that the variable name cannot start with a number or special symbols.
  • PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.

PHP Variable: Declaring string, integer, and float

Let’s see the example to store string, integer, and float values in PHP variables.

<?php  
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str <br/>";  
echo "integer is: $x <br/>";  
echo "float is: $y <br/>";  
?>  

Output:

string is: hello string
integer is: 200
float is: 44.6 

PHP Variable: Sum of two variables

<?php  
$x=5;  
$y=6;  
$z=$x+$y;  
echo $z;  
?>  

Output:

11

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name “color” is different from Color, COLOR, COLor etc.

<?php  
$color="red";  
echo "My car is " . $color . "<br>";  
echo "My house is " . $COLOR . "<br>";  
echo "My boat is " . $coLOR . "<br>";  
?>  

Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is 
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is 

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can’t be start with numbers and special symbols.

<?php  
$a="hello";//letter (valid)  
$_b="hello";//underscore (valid)  
  
echo "$a <br/> $_b";  
?>  

Output:

hello 
hello
<?php  
$4c="hello";//number (invalid)  
$*d="hello";//special symbol (invalid)  
  
echo "$4c <br/> $*d";  
?>  

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
 or '$' in C:\wamp\www\variableinvalid.php on line 2

PHP: Loosely typed language

PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.

PHP Echo and print

We frequently use the echo statement to display the output. There are two basic ways to get the output in PHP:

  • echo
  • print

echo and print are language constructs, and they never behave like a function. Therefore, there is no requirement for parentheses. However, both the statements can be used with or without parentheses. We can use these statements to output variables or strings.

Difference between echo and print

echo

  • echo is a statement, which is used to display the output.
  • echo can be used with or without parentheses.
  • echo does not return any value.
  • We can pass multiple strings separated by comma (,) in echo.
  • echo is faster than print statement.

print

  • print is also a statement, used as an alternative to echo at many times to display the output.
  • print can be used with or without parentheses.
  • print always returns an integer value, which is 1.
  • Using print, we cannot pass multiple arguments.
  • print is slower than echo statement.

You can see the difference between echo and print statements with the help of the following programs.

PHP echo is a language construct, not a function. Therefore, you don’t need to use parenthesis with it. But if you want to use more than one parameter, it is required to use parenthesis.

The syntax of PHP echo is given below:

  1. void echo ( string $arg1 [, string $… ] )  

PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are:

  • echo is a statement, which is used to display the output.
  • echo can be used with or without parentheses: echo(), and echo.
  • echo does not return any value.
  • We can pass multiple strings separated by a comma (,) in echo.
  • echo is faster than the print statement.

PHP echo: printing string

<?php  
echo "Hello by PHP echo";  
?>  

Output:

Hello by PHP echo

PHP echo: printing multi line string

<?php  
echo "Hello by PHP echo  
this is multi line  
text printed by   
PHP echo statement  
";  
?>  

Output:

Hello by PHP echo this is multi line text printed by PHP echo statement

PHP echo: printing escaping characters

<?php  
echo "Hello escape \"sequence\" characters";  
?>  

Output:

Hello escape "sequence" characters

PHP echo: printing variable value

<?php  
$msg="Hello JavaTpoint PHP";  
echo "Message is: $msg";    
?>  

Output:

Message is: Hello JavaTpoint PHP

PHP Print

Like PHP echo, PHP print is a language construct, so you don’t need to use parenthesis with the argument list. Print statement can be used with or without parentheses: print and print(). Unlike echo, it always returns 1.

The syntax of PHP print is given below:

  1. int print(string $arg)  

PHP print statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are:

  • print is a statement, used as an alternative to echo at many times to display the output.
  • print can be used with or without parentheses.
  • print always returns an integer value, which is 1.
  • Using print, we cannot pass multiple arguments.
  • print is slower than the echo statement.

PHP print: printing string

<?php  
print "Hello by PHP print ";  
print ("Hello by PHP print()");  
?>  

Output:

Hello by PHP print Hello by PHP print()

PHP print: printing multi line string

<?php  
print "Hello by PHP print  
this is multi line  
text printed by   
PHP print statement  
";  
?>  

Output:

Hello by PHP print this is multi line text printed by PHP print statement

PHP print: printing escaping characters

<?php  
print "Hello escape \"sequence\" characters by PHP print";  
?>  

Output:

Hello escape "sequence" characters by PHP print

PHP print: printing variable value

<?php  
$msg="Hello print() in PHP";  
print "Message is: $msg";    
?>  

Output:

Message is: Hello print() in PHP

JavaScript Variables

JavaScript Variable is an object(or a named memory space) that is used to store a value that can be used during program execution. A variable in JavaScript, just like in other programming languages, has a name, a value, and a memory address.

  • The name of the variable uniquely identifies the variable,
  • The value refers to data stored in the variable, and
  • The memory address refers to the memory location of the variable.

In other words, we can say that variable is a container that can be used to store value and you need to declare a variable before using it.

In JavaScript, the var keyword is used to declare a variable. Also, starting from ES6 we can also declare variables using the let keyword.

JavaScript Rules for Variable name

The following are some rules to keep in mind while declaring variables.

  • Variable names cannot contain spaces.
  • The first letter of the variable can be [a-z, A-Z], dollar sign ($) or underscore(_), after the first letter of name any digit [0-9] can be used.
  • Variable names are case sensitive. For example: var a and var A both are different.
  • We can use either var or let keyword to define variables.
  • We can not use reserved words as the name of the variables in JavaScript.

JavaScript Syntax for Declaring a Variable

Following is the syntax for declaring a variable and assigning values to it.

var variable_name;
// or
let variable_name;

We can also define a variable without using the semicolon too. Also, when we have to define multiple variables, we can do it like this:

// declaring 3 variables together
var x, y, z;

And as we have already learned that Dynamic typed is a JavaScript feature, so we do not have to worry about specifying the data type of the value which we will store in the variable. JavaScript automatically detects that.

JavaScript Variable Example:

Now let’s take a simple example where we will declare a variable and then assign it a value.

var employeeName;   // Declaring a variable

var employeeName = "Rahul";   // Declaring and assigning at the same time

You can initialize or assign a value to the variable at the time you declare the variable or you can just declare the variable and initialize that later on.

JavaScript: Types of Variables

JavaScript supports two types of variables, they are:

  • Local Variable
  • Global Variable

You can use them according to the requirement in the application. Let’s learn about both JavaScript Local variables and JavaScript Global variables with examples.

1. JavaScript Local Variable

JavaScript Local variable is a variable that is declared inside a code block or a function body or inside a loop body and it has scope within the code block or the function. In simple words, the scope of a local variable is between the opening and closing curly braces { }, when declared and defined inside a code block or a function body.

Starting from ES6 it is recommended to use the let keyword while declaring local variables.

Let’s take an example of it.

function someFunc() { let num = 007; // local variable. document.writeln(num); } // calling the function someFunc(); /* trying to access the variable outside its scope */ document.writeln(“/”); document.writeln(num);

2. JavaScript Global Variable

JavaScript Global Variable is a variable that is declared anywhere inside the script and has scope for the complete script execution. Global variables are not declared inside any block or function but can be used in any function, or block of code.

var num = 007; // global variable. function someFunc() { document.writeln(num); } // calling the function someFunc(); /* trying to access the global variable */ document.writeln(“/”); document.writeln(num);

Its recommended that we use the var keyword to declare the global variables, starting from ES6.