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

No comments:

Post a Comment