Functions in php
A function is a block of statements that can be used repeated in an execution. If we declare a function in php, it will not execute the code inside the function untill it is called. The php has already thousands of built-in functions. Not only the built-in functions, we can also create our own functions called the user defined function.
Creating a user defined function
Like other languages, a user defined function starts with the keyword function.
Syntax:
eg:
output:
This is a simple program without any parameters passed to the function. We can use the parameters to pass values to the function.
eg:
Output:
We can also pass more than one arguments to the function as belows:
eg:
Output:
The another keyword that is used inside a function is return. It is used to return a value from a function to outside the function. That is the returned value goes to the called function.
eg:
Output:
Syntax:
function function_name(parameter)
{
//Code to be executed
}
{
//Code to be executed
}
eg:
<?php
function simple()
{
echo "hello world";
}
simple();
?>
output:
hello world
This is a simple program without any parameters passed to the function. We can use the parameters to pass values to the function.
eg:
<?php
function simple($arg)
{
echo "$arg world<br>";
}
simple("hello");
simple("nice");
?>
Output:
hello world
nice world
nice world
We can also pass more than one arguments to the function as belows:
eg:
<?php
function simple($arg1,$arg2)
{
echo "$arg1 $arg2";
}
simple("hello","world");
?>
Output:
hello world
The another keyword that is used inside a function is return. It is used to return a value from a function to outside the function. That is the returned value goes to the called function.
eg:
<?php
function simple(int $a,int $b)
{
return $a+$b;
}
echo add(2,3);
?>
Output:
5
⇐Prev
Next⇒
Nice 👌
ReplyDelete