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.
No comments:
Post a Comment