Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Monday, 31 May 2021

Php: Return multiple values from a function

In Php, functions return single value. If you have a requirement to return multiple values, you can use either of following approaches.

 

a.   Returning an array from function

b.   Returning an object from the function

 

Returning an array from function

Example

function calc_arithmetic($var1,$var2){
    $sum = $var1 + $var2;
    $sub = $var1 - $var2;
    $mul = $var1 * $var2;
    $div = $var1 / $var2;

    return array(
        'sum'=>$sum,
        'sub'=>$sub,
        'mul'=>$mul,
        'div'=>$div
    );
}

 

Find the below working application.

 

function_return_array_demo.php

#!/usr/bin/php

<?php
    function calc_arithmetic($var1,$var2){
        $sum = $var1 + $var2;
        $sub = $var1 - $var2;
        $mul = $var1 * $var2;
        $div = $var1 / $var2;

        return array(
            'sum'=>$sum,
            'sub'=>$sub,
            'mul'=>$mul,
            'div'=>$div
        );
    }

    $a = 20;
    $b = 3;
    $result = calc_arithmetic($a, $b);

    echo "Sum of $a and $b is {$result['sum']}\n";
    echo "Subtraction of $a and $b is {$result['sub']}\n";
    echo "Multiplication of $a and $b is {$result['mul']}\n";
    echo "Division of $a and $b is {$result['div']}\n";
?>

 

Output

$./function_return_array_demo.php 

Sum of 20 and 3 is 23
Subtraction of 20 and 3 is 17
Multiplication of 20 and 3 is 60
Division of 20 and 3 is 6.6666666666667

 

Returning an object from function

Example

function calc_arithmetic($var1,$var2){
    $sum = $var1 + $var2;
    $sub = $var1 - $var2;
    $mul = $var1 * $var2;
    $div = $var1 / $var2;

    return new Arithmetic($sum, $sub, $mul,$div);
}

 

function_return_object_demo.php

#!/usr/bin/php

<?php

    class Arithmetic{
        public $sum;
        public $sub;
        public $mul;
        public $div;

        public function __construct($sum, $sub, $mul, $div){
            $this->sum = $sum;
            $this->sub = $sub;
            $this->mul = $mul;
            $this->div = $div;
        }
    }

    function calc_arithmetic($var1,$var2){
        $sum = $var1 + $var2;
        $sub = $var1 - $var2;
        $mul = $var1 * $var2;
        $div = $var1 / $var2;

        return new Arithmetic($sum, $sub, $mul,$div);
    }

    $a = 20;
    $b = 3;
    $result = calc_arithmetic($a, $b);

    echo "Sum of $a and $b is {$result->sum}\n";
    echo "Subtraction of $a and $b is {$result->sub}\n";
    echo "Multiplication of $a and $b is {$result->mul}\n";
    echo "Division of $a and $b is {$result->div}\n";
?>

 

Output

$./function_return_object_demo.php 

Sum of 20 and 3 is 23
Subtraction of 20 and 3 is 17
Multiplication of 20 and 3 is 60
Division of 20 and 3 is 6.6666666666667

 

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Monday, 26 April 2021

Php: Functions: pass the argument by reference

If you pass an argument to the function by reference, any changes made to the variable inside the function are visible outside also.

 

Example

function square(&$a){

    $a = $a * $a;

}

 

In the above snippet, square function expecting a variable reference(same is conveyed to php using &).

 

function_pass_by_reference.php

#!/usr/bin/php

<?php
    function square(&$a){
        $a = $a * $a;
    }

    $ele = 10;

    echo "Value of ele : $ele\n";
    echo "Calling square function\n";

    square($ele);
    echo "Value of ele : $ele\n";
?>

 

Output

$./function_pass_by_reference.php 

Value of ele : 10
Calling square function
Value of ele : 100

 

 

 

  

Previous                                                    Next                                                    Home

Sunday, 25 April 2021

Php: functions: return a value from function

Using ‘return’ keyword, you can return a value from function.

 

Example 1: Return welcome message from function.

function welcome_user($name)
{
    return "Hello $name\n";
}

 

Example 2: Function return sum of two numbers.

function sum($a, $b)
{
    return $a + $b;
}

 

function_return_value_demo.php

#!/usr/bin/php

<?php

function welcome_user($name)
{
    return "Hello $name\n";
}

function sum($a, $b)
{
    return $a + $b;
}

$welcome_message = welcome_user("Krishna");
$result = sum(10, 20);

echo $welcome_message;
echo "Sum of 10 and 20 is : $result";
?>

 

Output

$./function_return_value_demo.php 

Hello Krishna
Sum of 10 and 20 is : 3

 

Can I return any type of data from a function?

Yes, you can return any type of data (it can be a number, Boolean, array, string, object etc.,) from a function.

 

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Saturday, 24 April 2021

Php: Access variables defined outside of a function

There are two ways to access the variables defined outside of a function.

a.   Using global keyword

b.   Using $GLOBALS array

 

Using global keyword

 

Syntax

global $variable_name;

 

Use the keyword ‘global’ followed by variable name to access the variable defined outside of a function.

 

Example

$name = 'Krishna';

$age = 32;

$msg = 'Hello';

 

global_variable_demo.php

#!/usr/bin/php

<?php
   function welcome_me(){
        global $name;
        global $age;
        global $msg;

        $msg = $msg . ' ' . $name . ', ' . 'you are ' . $age . ' years old';
   }

   $name = 'Krishna';
   $age = 32;
   $msg = 'Hello';

   welcome_me();
   echo $msg;

?>

Output

$./global_variable_demo.php 

Hello Krishna, you are 32 years old


Using $GLOBALS array

 

Syntax

$GLOBALS['variable_name']

 

Example

$my_name =  $GLOBALS['name'];

$my_age =  $GLOBALS['age'];

$my_msg =  $GLOBALS['msg'];

 

Find the below working application.

 

globals_array_demo.php

#!/usr/bin/php

<?php
   function welcome_me(){
        $my_name =  $GLOBALS['name'];
        $my_age =  $GLOBALS['age'];
        $my_msg =  $GLOBALS['msg'];

        $GLOBALS['msg'] = $my_msg . ' ' . $my_name . ', ' . 'you are ' . $my_age . ' years old';
   }

   $name = 'Krishna';
   $age = 32;
   $msg = 'Hello';

   welcome_me();
   echo $msg;

?>


Output

$./globals_array_demo.php 

Hello Krishna, you are 32 years old







 

 

Previous                                                    Next                                                    Home

Php: functions

Function is a block of statements, that can be reused any number of times. Function is defined using ‘function’ keyword followed by funcation name, parenthesis and parameters.

 

Syntax

function function_name(parameter1, parameter2....parameterN){
    ......
    ......
}

 

Example

function print_array($arr)
{
    echo "Elements in the array";
    foreach ($arr as $key => $value) {
        echo "$key => $value\n";
    }

    echo "\n\n";
}

 

Above snippet defines a function named ‘print_array’ which takes an array as argument and print contents of the array.

 

How to call the function?

You can call the function with its name by passing arguments if any.

 

Example

print_array($arr1);

 

Find the below working application.

 

function_demo.php

 

#!/usr/bin/php

<?php

function print_array($arr)
{
    echo "Elements in the array";
    foreach ($arr as $key => $value) {
        echo "$key => $value\n";
    }

    echo "\n\n";
}

$arr1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

$arr2 = array(
    2,
    3,
    'Hello',
    true
);

print_array($arr1);
print_array($arr2);
?>

 

Output

#!/usr/bin/php

<?php

function print_array($arr)
{
    echo "Elements in the array";
    foreach ($arr as $key => $value) {
        echo "$key => $value\n";
    }

    echo "\n\n";
}

$arr1 = [
    "id" => 1,
    "age" => 32,
    "name" => "Sailu",
    "male" => false
];

$arr2 = array(
    2,
    3,
    'Hello',
    true
);

print_array($arr1);
print_array($arr2);
?>

Variable outside of a function is not accessible inside the function

 

function_demo_2.php

#!/usr/bin/php

<?php

$name = "Krishna";

function welcome_user(){
    echo "Hello Mr.$name, how are you";
}

welcome_user();
?>


Output

$./function_demo_2.php 

Hello Mr., how are you



As you see the output, even though we assign a value to the variable $name, since it is defined outside of the function it is not accessible.

 

But there is a way to access the variables defined outside of a function. I will discuss about this in my next post.





 

 

 

Previous                                                    Next                                                    Home

Sunday, 4 April 2021

Php: Basic array function

In upcoming posts, I am going to cover basic array functions. If you are interested to see all the available array functions in php, I would request you to go through below link.

https://www.php.net/manual/en/ref.array.php

 

Previous                                                    Next                                                    Home

Saturday, 22 December 2018

Is function keyword required in defining functions in object literals?

From EcmaScript 6 onwards, you no need to specify function keyword while defining the functions in object literals.

Let me explain with an example.

HelloWorld.js
var emp1 = {
  firstName : "Krishna",
  lastName : "Gurram",
  
  printEmployeeInfo : function(){
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }
}

emp1.printEmployeeInfo();

Output
firstName : Krishna
lastName : Gurram

As you see HelloWorld.js file, I defined printEmployeeInfo method using function keyword. From EcmaScript 6 onwards, you no need to use function keyword.

You can define printEmployeeInfo() method like below.

printEmployeeInfo(){
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }

HelloWorld.js

var emp1 = {
  firstName : "Krishna",
  lastName : "Gurram",
  
  printEmployeeInfo(){
    console.log("firstName : " + this.firstName);
    console.log("lastName : " + this.lastName);
  }
}

emp1.printEmployeeInfo();


Previous                                                 Next                                                 Home

Sunday, 9 December 2018

JavaScript: method vs function

A method is a function that is property of an object.

HelloWorld.js

var employee = {
    name : "krishna",
    age : 29,
    toString: function(){
        return "name : " + this.name + ", age : " + this.age + "]";
    }
}

function square(num){
    return num * num;
}

console.log(employee);
console.log(`Square of 10 is ${square(10)}`);

In the above example, toString() is a method, whereas square is a function.

Previous                                                 Next                                                 Home