Setup Menus in Admin Panel

  • No products in the cart.

  • LOGIN

PHP functions

A function is a block of code which can be called from any point in a script after it has been declared.A key benefit of using functions is that they can be reused many times.It can take input as argument list and return value.Php comes with hundreds of ready-made,built-in functios,making it a very rich language.

 

Advantages of using PHP functions:

Portable:

PHP can run for almost every server and most platforms.You can run it in Apache,IIS,etc.This means ”written once run anywhere”.

Cost:

PHP itself is free, and the majority of items it works with out of the box(Apache,MYSQL,PostgreSQL) are free.This gives your project a very low initial cost threshold.

Code Reusability:

PHP functions are defined once and can be invoked many times,like in other programming languages.

Easy to understand:

PHP functions understand the flow of the application because every logic is divided in the form of functions.

 

Defining a function:

The general syntax for a functios is as follows:

code:-

<?php
function function_name(param_1, .... , param_n)
{
Statement_1;
Statement_2;
...
Statement_n;
Return retun_value;
}
?>

 

I will explain all the related terms.The first line of the syntax indicates the following:

  • A definition starts with the word function.
  • A name follows, which must start with a letter or underscore, followed by any
  • number of letters, numbers, or underscores.
  • The parentheses are required.
  • One or more parameters, separated by commas, are optional.

 

Function names are case-insensitive.So, all of the following strings can refer to the

print function: PRINT, Print, and PrInT.

The opening curly brace starts the statements that will execute when you call the

function; a matching curly brace must close it. These statements may include one or

more return statements, which force the function to cease execution and return to

the calling code. If a value is attached to the return statement, the calling code can

retrieve it, as we’ll see next.

 

Creating a simple function:

Creating a php function is very easy.Let’s create two functions that will print the message “welcome to phphelp.net”.While creating a function its name start with keyword function and all the PHP code should be inside the curley braces { and } as in example below:-

Code:

      <?php
        /* Defining a PHP Function */
         function writeMessage() {
         echo "Welcome to our website phphelp.net!";
         }
         /* Calling a PHP Function */
         writeMessage();
         ?>

 

 Result:

Welcome to our website phphelp.net!

 

PHP Parameterized Function:

PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function.

They are specified inside the parentheses, after the function name.

The output depends upon the dynamic values passed as the parameters into the function.

Example:

Addition of two parameters.

In this example, we have passed two parameters $a and $b inside two functions add() and sub().]

Code:

<?php 
    function addFunction($a, $b) { 
    $sum = $a + $b; 
    echo "Sum of two numbers is = $sum <br><br>"; 
    }  
   addFunction(1, 2); 
?>

 

Output:

Sum of two numbers is 3

 

PHP Call By Value

PHP allows you to call function by value and reference both. In case of PHP call by value, actual value is not modified if it is modified inside the function.

 

Example:

In this example, variable $str is passed to the msg function where it is concatenated with ‘This is phphelp.net’ string. But, printing $str variable results ‘Welcome’ only. It is because changes are done in the local variable $str1 only. It doesn’t reflect to $str variable.

Code

<?php 
function msg($str1) 
{ 
    $str1 .= ‘This is phphelp.net’; 
} 
$str = 'Welcome '; 
msg($str); 
echo $str; 
?>

Output:

Welcome

 

PHP call by reference:

Call  by reference allows you to override the normal scoping rules and give a function direct access to a variable. To be passed by reference, the argument must be a variable; you indicate that a particular argument of a function will be passed by reference by preceding the variable name in the parameter list with an ampersand (&).

Here, the variable $str is passed to the msg function where it is concatenated with ‘Phphelp.net’ string. Here, printing $str variable results ‘Welcome Phphelp.net’. It is because changes are done in the actual variable $str.

Example:

<?php 
function msg(&$str1) 
{ 
   $str1 .= ‘Phphelp.net’; 
} 
$str = 'Welcome'; 
msg($str); 
echo $str; 
?>

Output:

Welcome Phphelp.net

 

PHP defaults arguments:

Similar to the programming language C++,it also allows to define a default argument. In such case, if you don’t pass any value to the function, it will use default argument value.

Example1:

function dolt($name)
{
echo “Hello”.$name;
}
dolt();      // a warning is emitted
dolt(“Hi”,”phphelp”);   //This is valid.

 

It is preferable that the arguments with default values should be the last arguments passed to the function.

PHP emits a warning if the number of the arguments passed is not the same the number of arguments in the function declaration.

PHP does not throw any warning in case the number is bigger than the arguments in the function declaration.

 

Example 2:

<?php 
function add($num1=2,$num2=2){ 
$sum=$num1+$num2; 
echo "Sum  is: $sum<br/>"; 
} 
add(); 
add(10); 
add(5,5); 
?>

 

Result:

Sum is: 4
Sum is: 12
Sum is: 10

 

PHP variable length argument function:

PHP allows you to create a function with unlimted number of arguments. It means you can pass 0, 1,2 or n number of arguments in function.

But in PHP version 5.6 or later version you need to use 3 dots before the argument name.

 

Example

<?php 
function add(...$numbers) { 
    $sum = 0; 
    foreach ($numbers as $n) { 
    $sum += $n; 
   } 
   return $sum; 
} 
echo add(1, 2, 3); 
?>

 

Result:

6

 

 

PHP Recursive function

A recursive function is a function that calls itself.

Recursion occurs when something contains, or uses   a similar version of itself.In programming,it happens when a function is having a call to itself.

The factorial problem:-

5! = 5*4*3*2*1
   =120

 

Example:

function fact($n) {
  if ($n === 0) { // our base case
    return 1;
  }
  else {
     return $n * fact($n-1); // calling itself again and again
  }
}

 

 

ASSIGNMENT : Give examples for call by value and call by reference fucntions in php. MARKS : 10  DURATION : 1 week, 3 days

ASSIGNMENT : Write the advantages of using PHP functions. MARKS : 5  DURATION : 10 minutes

ASSIGNMENT : Write examples program for user defined function. MARKS : 5  DURATION : 5 minutes

SEE ALL Add a note
YOU
Add your Comment
 

Advanced Course Search Widget

Popular Courses

Course Categories

© PHPhelp. 2002 - 2018 All rights reserved.
X