PHP functions

      No Comments on PHP functions

PHP functions are the real power of PHP . It has more than 1000 built-in functions.

PHP functions

  • Besides built-in functions, we can create our own function in PHP
  • When we want to execute a same block of code multiple times, function are used.
  • Functions are called by writing
    <?php function_name(); ?>

Creating a User defined function

A user defined function is declared using fucntion keyword.

Syntax:

function functionName() {
    code to be executed;
} 

Example:

<?php
function writeMsg()
{
   echo "Hello ! Scanfcode";
}
  
writerMsg();
?>

Output:

Hello !Scanfcode

We have created a function name writeMsg(); ,the opening brace ‘{‘ marks the begining of the function code and closing brace ‘}’ indicates the ending of the function code. The statement echo “Hello ! Scanfcode” is what this function does.To call the function just write the name.

PHP function arguments

Information can be passed to a function as an argument. Argument s are just like 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.

The following example illustrates the function writeName($wname), $wname is passed as an argument. The function prints the name passed to it.

<?php
function writeName($wname)
{
  echo $wname;
}
 writeName("Scanfcode");
 writeName("Code");
 writeName("PHP");
?>

Output:

Scanfcode
Code
PHP

Default arguments

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

<?php
function showAge($age=20)
{
  echo $age;
}
 showAge(); //prints default value
 showAge(18);
 showAge(10);
?>

Output:

20
18
10

Returning value

return keyword can be used in a function to return any value.

 <?php
function sum($x, $y) {
    $z = $x + $y;
    return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

Output:

5+10=15
7+13=20
2+4=6

Leave a Reply

Your email address will not be published. Required fields are marked *