call function in PHP

We can create our own function inside our PHP programs for re-usability and making our code optimization purposes. Functions are a block of codes executed only when calling. Codes inside a PHP function will execute when we call a function in PHP program.

We can create a function using the “function” statement. Its syntax will look like

function functioname()
{
Operation Codes here;
}

Here is a simple example of using a function in PHP

<?php
function message()
{
echo "Welcome to phpmysqlbrain.com";
}
$name="Guest";
echo "Hi ".$name." ";
message();
?>

Its output will be
Hi Guest Welcome to phpmysqlbrain.com
You can easily understand whats happening when we call that function.

Now we can look at some more deep about functions. We can use parameters to pass the values to a function. Also function can return the values ( results ).

See the following sample PHP program for passing a value to a function

<?php
function message($data)
{
echo "Hi ".$data." Welcome to phpmysqlbrain.com";
}
$name="Guest";
message($name);
?>

Its output will also same as our previous example
Hi Guest Welcome to phpmysqlbrain.com
Here we can see that we have passed the $name variable to the function message() . And function received that variable using the variable $data. Like this we can pass any number of parameters while calling a function.

Now watch the following sample PHP program with passing more than one parameters and return value from a function

<?php
function multiply($a,$b)
{
$result=$a * $b;
return $result;
}
$x = 10;
$y = 20;
$z = multiply($x,$y) + 1;
echo $z;
?>

Output of this program will be:
201

Here call multiply function passing the values $x and $ y. function multiply receiving these values with variables $a and $b accordingly. Then its doing the calculation parts and return the result.

Share
Share
Share