PHP Functions

by Hiroshi on June 21, 2008

in PHP Basics, PHP Functions

A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!

Suppose you have to use something again and again in PHP code. Then we can create a function and put that thing in function and recall it in the code whenever, wherever and how-much-ever we want it. This saves our time and code size.

<?php
function myCompanyMotto()
{
    echo "We deliver quality, not quantity!<br />";
}
echo "Welcome to The Company<br />";
myCompanyMotto();
echo "Well, thanks for visiting! <br />";
echo "and remember... <br />";
myCompanyMotto();
 
// Output:
// Welcome to The Company
// We deliver quality, not quantity!
// Well, thanks for visiting!
// and remember...
// We deliver quality, not quantity!
?>

In the above example we created a function named as myCompanyMotto() and we stored the statement “We deliver quality, not quantity!” with a line break and we are using it in the code twice and we can use that statement as many times in code as we want by just calling that function myCompanyMotto();.

<?php
function addition($a, $b)
{
$c = $a + $b;
return $c;
}
$num1 = 4;
$num2 = 7;
echo "The result is " . addition($num1, $num2) ;
 
// Output: The result is 11
?>
<?php
function addition($a, $b = 9){
$c = $a + $b;
return $c;
}
$num1 = 36;
$num2 = 7;
$num3 = 34;
echo "The result is " . addition($num1, $num2) ;
echo " <br />The result second time is " . addition($num1, num3) ;
echo " <br />The result third time is " . addition($num1) ;
 
// Output:
// The result is 43
// The result second time is 36
// The result third time is 45
?>

– Always start your function with the keyword function.
– Remember that your function’s code must be between the “{” and the “}”
– When you are using your function, be sure you spell the function name correctly.

Related Posts

Previous post:

Next post: