0% found this document useful (0 votes)
7 views

Functions 1

functions

Uploaded by

irfanahmed.dba
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Functions 1

functions

Uploaded by

irfanahmed.dba
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

A function is a piece of code which takes one more input in the form of parameter and does some

processing and returns a value.

In PHP, we can define Conditional function, Function within Function and Recursive function
also.
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the
use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand
the flow of the application because every logic is divided in the form of functions.

There are two parts which should be clear to you −


Creating a PHP Function
Calling a PHP Function

PHP User-defined Functions


A user-defined function declaration starts with the word function:
Syntax
function functionname()
{
//code to be executed
}
<?php
function writeMsg()
{
echo "color:brown">"Hello world!";
}
writeMsg();
?>

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
<?php
functionfamilyName($fname)
{
Echo"$fnameRefsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName(“Kai Jim");
familyName("Borge");
?>

The following example has a function with two arguments ($fname and $year):
<?php
functionfamilyName($fname, $year)
{
echo "$fnameRefsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:

Example
<?php
functionsetHeight($minheight = 50)
{
echo "The height is : $minheight<br>";
}

setHeight(350);
setHeight(); "color:green">// will use the default value of 50
setHeight(135);
setHeight(80);
?>

You might also like