PHP: Function, Conditionals and Scope

·

2 min read

Function Definition

A function is defined using the 'function' keyword similar to JavaScript.

function myFun()
{
    echo "Hello World";
}
// Output: Hello World
myFun();

Default Parameter

The parameters in a function can be given a default value which will be used when the user doesn't provide any argument to the function. The corresponding default parameters are replaced if the user provides some arguments.

function myFun2($greet = "Hello", $name="Ram")
{
    echo "$greet! $name. How are you?";
}
// Output: Hello! Ram. How are you? 
myFun2();
// Output: Hi! Ram. How are you? 
myFun2("Hi");
// Output: Hi! Shyam. How are you? 
myFun2("Hi", "Shyam");

Conditional Statement

If, If-Else and Else Statement are similar to other programming languages in PHP.

$array1 = [
    ["fName"=>"James", "age"=>32],
    ["fName"=>"David", "age"=>28],
    ["fName"=>"Olivia", "age"=>21]
];
// Iterate through each array elements
foreach($array1 as $person)
{
    // Run one statement according to condition
    if($person["age"] < 30)
    {
        echo $person["fName"] . " is under age 30: "; 
    }
    else if($person["age"] > 30)
    {
        echo $person["fName"] . " is above age 30: "; 
    }
    else
    {
        echo $person["fName"] . " is of age 30: "; 
    }
    // Run this statement without anu condition
    echo "Age: {$person["age"]}";
}

Variable Scope

Variable scope is the region of code where we can access the variable. Hence, we can't access the variable from outside it's scope.

// Local Variable 
function fun1()
{
    $name = "Ram";                // Local Variable
    echo "Hello $name";
}
// Output: Hello Ram
fun1();
// echo $name;                    // Can't Access Local Variable

To use the global variable inside a function, we can use the 'global' keyword.

$name = "Shyam";                // Global Variable
function fun2()
{
    global $name;                // Get access to global variable
    $name = "Hari";            
    echo "Hello $name";
}
// Output: Hello Hari
fun2();
// Output: Hari
echo $name;

We can also, access the global variable by passing it as an argument in the function.

$name = "Shyam";                // Global Variable
function fun3($name)
{
    $name = "Gopal";
    echo "Hello $name";
}
// Output: Hello Gopal
fun3($name);                    // Passing by value
// Output: Shyam
echo $name;                     // Variable not modified

Even though we accessed the global variable but we couldn't update the global variable outside the scope of the function. So, we need to pass the reference of the global variable to actually modify it.

$name = "Shyam";                // Global Variable
// Passing by reference
function fun4(&$name)           
{    
    $name = "Giver";
    echo "Hello $name";
}
// Output: Hello Giver
fun4($name);                    
// Output: Giver
echo $name;                     // Variable modified