SlideShare a Scribd company logo
UNIT – 3
FUNCTIONS IN PHP



                             Dr. P S V S Sridhar
                          Assistant Professor (SS)
                      Centre for Information Technology




        | Jan 2013|                                       © 2012 UPES
Functions
 A function is a self-contained block of statements that performs a specific
  task . Functions are most useful when you need to use the same code in
  more than one place. Reusing existing code reduces costs, increases
  reliability, and improves consistency. Ideally, combining existing reusable
  components, with a minimum of development from scratch creates a new
  project. If you find that your code files are getting longer, harder to
  understand, and more difficult to manage, however, it may be an
  indication that you should start wrapping some of your code up into
  functions.
Some of the properties of a function:
 has a unique name.
 is independent and it can perform its task without intervention from or
  interfering with other parts of the program .
 can take some inputs(i.e arguments) for performing a task.
 returns a value to the calling program. This is optional and depends upon
  the task your function is going to accomplish.
           Jul 2012
            Jan 2013                                                    © 2012 UPES
Functions

 Functions are the heart of a well-organized script, making code easy to
  read and reuse.
 The basic syntax for using (or calling) a function is:
   function_name(expression_1, expression_2, ..., expression_n)
 sqrt(9); // square root function, evaluates to 3
 rand(10, 10 + 10); // random number between 10 and 20
 strlen(“This has 22 characters”); // returns the number 22
 pi(); // returns the approximate value of pi
 strrev (" .dlrow olleH"); //returns Hellow world.
 str_repeat("Hip ", 2);   //returns Hip two times
 strtoupper("hooray!"); //returns in capital HOORAY
 phpinfo() function prints out the internal configuration capabilities of your particular
  PHP installation


              Jul 2012
               Jan 2013                                                             © 2012 UPES
Built-in Functions in PHP
  Every language has a set of built-in functions (for example, string
   functions). For example: echo(“PHP”);
  print(“It is a server side programming language”);
  Some of the Array functions in PHP are:
  array() ◦ To Create an array
  sort() ◦ Sorts an array
  array_unique() ◦ Removes duplicate values from an array
  count() ◦ Counts no of elements in an array
  array_reverse() ◦ Returns an array in the reverse order




           Jul 2012
            Jan 2013                                                     © 2012 UPES
Built-in Functions in PHP
  Some of the character functions in PHP are:
  ctype_upper() ◦ Checks if all of the characters in the provided string are
   uppercase characters, return as 1.
  ctype_digit() ◦ Checks if all of the characters in the provided string, text,
   are numerical.
  ctype_alpha() ◦ Checks if all of the characters in the provided string,
   text, are alphabetic
  ctype_alnum() - Check for alphanumeric character(s)
  ctype_xdigit() - Check for character(s) representing a hexadecimal digit
  is_numeric() - Finds whether a variable is a number or a numeric string
  is_int() - Find whether the type of a variable is integer
  is_string() - Find whether the type of a variable is string


           Jul 2012
            Jan 2013                                                     © 2012 UPES
User defined functions
 A function is a way of wrapping up a chunk of code and giving that chunk
  a name, so that you can use that chunk later in just one line of code.
  Functions are most useful when you will be using the code in more than
  one place, but they can be helpful even in one-use situations, because
  they can make your code much more readable.
 function function-name ($argument-1, $argument-2, ..)
  {   statement-1; statement-2; ...     }
 That is, function definitions have four parts:
 The special word function
 The name that you want to give your function
 The function’s parameter list — dollar-sign variables separated by
  commas
 The function body — a brace-enclosed set of statements


           Jul 2012
            Jan 2013                                                   © 2012 UPES
Function definition example
function better_deal ($amount_1, $price_1,$amount_2, $price_2)
{
    $per_amount_1 = $price_1 / $amount_1;
    $per_amount_2 = $price_2 / $amount_2;
     return($per_amount_1 < $per_amount_2);
}
$liters_1 = 1.0; $price_1 = 1.59; $liters_2 = 1.5; $price_2 = 2.09;
if (better_deal($liters_1, $price_1, $liters_2, $price_2))
    print(“The first deal is better!<BR>”);
else
    print(“The second deal is better!<BR>”);

             Jul 2012
              Jan 2013                                                © 2012 UPES
Call by Value
     The argument variable within the function is an "alias" to the actual
      variable
     But even further, the alias is to a *copy* of the actual variable in the
      function call
       function double($alias)
         {     $alias = $alias * 2;   return $alias;}
       $val = 10;
       $dval = double($val);
       echo "Value = $val Doubled = $dvaln";


 Output:

  Value = 10 Doubled = 20
             Jul 2012
              Jan 2013                                                    © 2012 UPES
Call by Reference
  Sometimes we want a function to change one of its arguments - so we
   indicate that an argument is "by reference" using ( & )
        function triple(&$alias)
        {      $alias = $alias * 3;}
        $val = 10;
        triple($val);
        echo "Triple = $valn";
 Output:
  Triple = 30




            Jul 2012
             Jan 2013                                             © 2012 UPES
Argument number mismatches
  Too few arguments
  If you supply fewer actual parameters than formal parameters, PHP
   will treat the unfilled formal parameters as if they were unbound
   variables. However, under the usual settings for error reporting in
   PHP6, you will also see a warning printed to the browser.
  Too many arguments
  If you hand too many arguments to a function, the excess arguments
   will simply be ignored, even when error reporting is set to E_ALL.




          Jul 2012
           Jan 2013                                               © 2012 UPES
Passing Arrays to Functions
 <?php
 $scores = array(57,58,39,67,59);
 average($scores);
 function average($array)
 {       $t = 0;
         foreach($array as $val)
         $t = $t + $val;
         if(count($array > 0))
                       echo "The average is ", $t/count($array);
         else
                       echo "No elements to average";
 }
 ?>

           Jul 2012
            Jan 2013                                               © 2012 UPES
Returning Arrays
 <?php
 $data1 = create_array(3);
 print_r($data1);
 $data2 = create_array(4);
 print_r($data2);
 function create_array($number)
 {
         for($counter = 0; $counter < $number; $counter++)
         {               $array[] = $counter;   }
         return $array;
 }
 ?>

             Jul 2012
              Jan 2013                                       © 2012 UPES
PHP Variable Scopes
  The scope of a variable is the part of the script where the variable can
   be referenced/used.
  PHP has four different variable scopes:
  local
  global
  static
  parameter




            Jul 2012
             Jan 2013                                                  © 2012 UPES
Functions and variable scope
 The scope of a variable defined inside a function is local by default,
  meaning that it has no connection with the meaning of any variables
  outside the function.
 The syntax of this declaration is simply the word global, followed by a
  comma-delimited list of the variables that should be treated that way, with
  a terminating semicolon.            Ex2:
                                     <?php
 global $count1, $count2;           $x=5; // global scope
Ex1:                                 $y=10; // global scope
<?php
                                     function myTest()
function myfunction()
                                     {
{                                    global $x,$y;
    $GLOBALS["n1"] = 10;             $y=$x+$y;
                                     }
}
$n1 = 20;                            myTest();
myfunction();                        echo $y; // outputs 15
                                     ?>
echo $n1;
                Jul 2012
                 Jan 2013                                                  © 2012 UPES
Static variables
  The static keyword allows for an initial assignment, which has an
   effect only if the function has not been called before. The first time the
   variable executes initial value assigned.
  The second time the function is called, it has the value it had at the
   end of the last execution.
 <?php
 function myTest()
 {
     static $x=0;
     echo $x;
     $x++;                                  Output:
 }                                          012
 myTest();
 myTest();
 myTest();
 ?>
                Jul 2012
                 Jan 2013                                                © 2012 UPES
Example
 function SayMyABCs3 ()
 {
 static $count = 0; //assignment only if first time called
 $limit = $count + 10;
 while ($count < $limit)
 {
 print(chr(ord(‘A’) + $count)); // chr () converts ASCII to char ord() returns ASCII value of char
 $count = $count + 1;
                                                             Output:
 }
                                                             ABCDEFGHIJ
 print(“<BR>Now I know $count letters<BR>”);
                                                             Now I know 10 letters
 }                                                           Now I’ve made 1 function call(s).
 $count = 0;                                                 KLMNOPQRST
 SayMyABCs3();                                               Now I know 20 letters
 $count = $count + 1;                                        Now I’ve made 2 function call(s).
 print(“Now I’ve made $count function call(s).<BR>”);
 SayMyABCs3();
 $count = $count + 1;
 print(“Now I’ve made $count function call(s).<BR>”);
               Jul 2012
                Jan 2013                                                                             © 2012 UPES
Parameter Scope
  A parameter is a local variable whose value is passed to the function
   by the calling code.
  Parameters are declared in a parameter list as part of the function
   declaration:
  <?php

   function myTest($x)
   {
   echo $x;
   }

   myTest(5);

   ?>


           Jul 2012
            Jan 2013                                                     © 2012 UPES
Include and require
  It’s very common to want to use the same set of functions across a set
   of web site pages, and the usual way to handle this is with either include
   or require, both of which import the contents of some other file into the
   file being executed. Using either one of these forms is vastly preferable
   to cloning your function definitions (that is, repeating them at the
   beginning of each page that uses them).
  For example, at the top of a PHP code file we might have lines like:
 include “basic-functions.inc”;
 include “advanced-function.inc”;
  Both include and require have the effect of splicing in the contents of
   their file into the PHP code at the point that they are called. The only
   difference between them is how they fail if the file cannot be found. The
   include construct will cause a warning to be printed, but processing
   of the script will continue; require, on the other hand, will cause a
   fatal error if the file cannot be found.

          Jul 2012
           Jan 2013                                                   © 2012 UPES
 include "header.php"; - Pull the file in here
 include_once "header.php"; - Pull the file in here unless it has
  already been pulled in before
 require "header.php"; - Pull in the file here and die if it is missing
 require_once "header.php"; - You can guess what this means...
 These can look like functions - require_once("header.php");




     Jul 2012
      Jan 2013                                                       © 2012 UPES
Missing functions
  Sometimes depending on the version or configuration of a particular
   PHP instance, some functions may be missing. We can check that.


   if (function_exists("array_combine"))
       {       echo "Function exists";}
   else
          {     echo "Function does not exist";}




              Jul 2012
               Jan 2013                                             © 2012 UPES
Variable functions
 In PHP we can assign variable value as a function name.
 <?php
 $function_variable = "red";
 $function_variable();
 $function_variable = "white";
 $function_variable("In white() now");
 function red()
 {
          echo "In red() now";
 }
 function white($argument)
 {
          echo $argument;
 }
            Jul 2012
             Jan 2013                                      © 2012 UPES
 ?>
Nested functions
 <?php                       or   <?php
                                  outer_function();
 outer_function();                function outer_function()
                                  {
 inner_function();
                                            echo "Outer function";
 function outer_function()                   inner_function();
                                  }
 {                                function inner_function()
                                  {
         echo "Outer function";
                                            echo "inner function";
 function inner_function()        }
                                  ?>
 {
         echo "inner function";
 }
 }
 ?>
          Jul 2012
           Jan 2013                                         © 2012 UPES
Passing Variable Number of Arguments
   func_num_args – Returns the number of arguments passed
   func_get_arg – Returns a single argument
   func_get_args – Returns all arguments in an array
  <?php
  connector('How','are','things');
  function connector()
  {
  $data = '';
  $arguments = func_get_args();
  for ($loop_index = 0; $loop_index <func_num_args(); $loop_index++)
  $data .= $arguments[$loop_index] . ' ';
  echo $data;                                output:
  }                                          How are things
  ?>            Jul 2012                                               © 2012 UPES
                 Jan 2013
Jul 2012
 Jan 2013   © 2012 UPES

More Related Content

What's hot (20)

HTML - Form
HTML - FormHTML - Form
HTML - Form
Hari Setiaji
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
Html
HtmlHtml
Html
Lakshmy TM
 
Php string function
Php string function Php string function
Php string function
Ravi Bhadauria
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 
PHP CONDITIONAL STATEMENTS AND LOOPING.ppt
PHP CONDITIONAL STATEMENTS AND LOOPING.pptPHP CONDITIONAL STATEMENTS AND LOOPING.ppt
PHP CONDITIONAL STATEMENTS AND LOOPING.ppt
rehna9
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
Dhananjay Goel
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
Maruf Abdullah (Rion)
 
MySQL
MySQLMySQL
MySQL
Gouthaman V
 
05 junit
05 junit05 junit
05 junit
mha4
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
baabtra.com - No. 1 supplier of quality freshers
 
[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens
OWASP
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
Elizabeth Thomas
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
Vineet Kumar Saini
 

Similar to PHP Unit 3 functions_in_php_2 (20)

Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
Ashish Chamoli
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptxPHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
Mohd Harris Ahmad Jaal
 
PHP variables
PHP  variablesPHP  variables
PHP variables
Siddique Ibrahim
 
Web Design EJ3
Web Design EJ3Web Design EJ3
Web Design EJ3
Aram Mohammed
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
Subhasis Nayak
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen Poreya
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
ShishirKantSingh1
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functions
vishnupriyapm4
 
Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
Japneet9
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam
 
Php
PhpPhp
Php
Yoga Raja
 
Php functions
Php functionsPhp functions
Php functions
JIGAR MAKHIJA
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
Ashish Chamoli
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptxPHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
Mohd Harris Ahmad Jaal
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen Poreya
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functions
vishnupriyapm4
 
Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
Japneet9
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam
 
Ad

More from Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
Kumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
Kumar
 
region-filling
region-fillingregion-filling
region-filling
Kumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
Kumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
Kumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
Kumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
Kumar
 
Xml basics
Xml basicsXml basics
Xml basics
Kumar
 
XML Schema
XML SchemaXML Schema
XML Schema
Kumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
Kumar
 
DTD
DTDDTD
DTD
Kumar
 
Applying xml
Applying xmlApplying xml
Applying xml
Kumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
Kumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
Kumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
Kumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
Kumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
Kumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
Kumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
Kumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
Kumar
 
Graphics devices
Graphics devicesGraphics devices
Graphics devices
Kumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
Kumar
 
region-filling
region-fillingregion-filling
region-filling
Kumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
Kumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
Kumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
Kumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
Kumar
 
Xml basics
Xml basicsXml basics
Xml basics
Kumar
 
XML Schema
XML SchemaXML Schema
XML Schema
Kumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
Kumar
 
Applying xml
Applying xmlApplying xml
Applying xml
Kumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
Kumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
Kumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
Kumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
Kumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
Kumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
Kumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
Kumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
Kumar
 
Ad

PHP Unit 3 functions_in_php_2

  • 1. UNIT – 3 FUNCTIONS IN PHP Dr. P S V S Sridhar Assistant Professor (SS) Centre for Information Technology | Jan 2013| © 2012 UPES
  • 2. Functions  A function is a self-contained block of statements that performs a specific task . Functions are most useful when you need to use the same code in more than one place. Reusing existing code reduces costs, increases reliability, and improves consistency. Ideally, combining existing reusable components, with a minimum of development from scratch creates a new project. If you find that your code files are getting longer, harder to understand, and more difficult to manage, however, it may be an indication that you should start wrapping some of your code up into functions. Some of the properties of a function:  has a unique name.  is independent and it can perform its task without intervention from or interfering with other parts of the program .  can take some inputs(i.e arguments) for performing a task.  returns a value to the calling program. This is optional and depends upon the task your function is going to accomplish. Jul 2012 Jan 2013 © 2012 UPES
  • 3. Functions  Functions are the heart of a well-organized script, making code easy to read and reuse.  The basic syntax for using (or calling) a function is: function_name(expression_1, expression_2, ..., expression_n)  sqrt(9); // square root function, evaluates to 3  rand(10, 10 + 10); // random number between 10 and 20  strlen(“This has 22 characters”); // returns the number 22  pi(); // returns the approximate value of pi  strrev (" .dlrow olleH"); //returns Hellow world.  str_repeat("Hip ", 2); //returns Hip two times  strtoupper("hooray!"); //returns in capital HOORAY  phpinfo() function prints out the internal configuration capabilities of your particular PHP installation Jul 2012 Jan 2013 © 2012 UPES
  • 4. Built-in Functions in PHP  Every language has a set of built-in functions (for example, string functions). For example: echo(“PHP”);  print(“It is a server side programming language”);  Some of the Array functions in PHP are:  array() ◦ To Create an array  sort() ◦ Sorts an array  array_unique() ◦ Removes duplicate values from an array  count() ◦ Counts no of elements in an array  array_reverse() ◦ Returns an array in the reverse order Jul 2012 Jan 2013 © 2012 UPES
  • 5. Built-in Functions in PHP  Some of the character functions in PHP are:  ctype_upper() ◦ Checks if all of the characters in the provided string are uppercase characters, return as 1.  ctype_digit() ◦ Checks if all of the characters in the provided string, text, are numerical.  ctype_alpha() ◦ Checks if all of the characters in the provided string, text, are alphabetic  ctype_alnum() - Check for alphanumeric character(s)  ctype_xdigit() - Check for character(s) representing a hexadecimal digit  is_numeric() - Finds whether a variable is a number or a numeric string  is_int() - Find whether the type of a variable is integer  is_string() - Find whether the type of a variable is string Jul 2012 Jan 2013 © 2012 UPES
  • 6. User defined functions  A function is a way of wrapping up a chunk of code and giving that chunk a name, so that you can use that chunk later in just one line of code. Functions are most useful when you will be using the code in more than one place, but they can be helpful even in one-use situations, because they can make your code much more readable.  function function-name ($argument-1, $argument-2, ..) { statement-1; statement-2; ... }  That is, function definitions have four parts:  The special word function  The name that you want to give your function  The function’s parameter list — dollar-sign variables separated by commas  The function body — a brace-enclosed set of statements Jul 2012 Jan 2013 © 2012 UPES
  • 7. Function definition example function better_deal ($amount_1, $price_1,$amount_2, $price_2) { $per_amount_1 = $price_1 / $amount_1; $per_amount_2 = $price_2 / $amount_2; return($per_amount_1 < $per_amount_2); } $liters_1 = 1.0; $price_1 = 1.59; $liters_2 = 1.5; $price_2 = 2.09; if (better_deal($liters_1, $price_1, $liters_2, $price_2)) print(“The first deal is better!<BR>”); else print(“The second deal is better!<BR>”); Jul 2012 Jan 2013 © 2012 UPES
  • 8. Call by Value  The argument variable within the function is an "alias" to the actual variable  But even further, the alias is to a *copy* of the actual variable in the function call function double($alias) { $alias = $alias * 2; return $alias;} $val = 10; $dval = double($val); echo "Value = $val Doubled = $dvaln";  Output: Value = 10 Doubled = 20 Jul 2012 Jan 2013 © 2012 UPES
  • 9. Call by Reference  Sometimes we want a function to change one of its arguments - so we indicate that an argument is "by reference" using ( & ) function triple(&$alias) { $alias = $alias * 3;} $val = 10; triple($val); echo "Triple = $valn"; Output:  Triple = 30 Jul 2012 Jan 2013 © 2012 UPES
  • 10. Argument number mismatches  Too few arguments  If you supply fewer actual parameters than formal parameters, PHP will treat the unfilled formal parameters as if they were unbound variables. However, under the usual settings for error reporting in PHP6, you will also see a warning printed to the browser.  Too many arguments  If you hand too many arguments to a function, the excess arguments will simply be ignored, even when error reporting is set to E_ALL. Jul 2012 Jan 2013 © 2012 UPES
  • 11. Passing Arrays to Functions <?php $scores = array(57,58,39,67,59); average($scores); function average($array) { $t = 0; foreach($array as $val) $t = $t + $val; if(count($array > 0)) echo "The average is ", $t/count($array); else echo "No elements to average"; } ?> Jul 2012 Jan 2013 © 2012 UPES
  • 12. Returning Arrays <?php $data1 = create_array(3); print_r($data1); $data2 = create_array(4); print_r($data2); function create_array($number) { for($counter = 0; $counter < $number; $counter++) { $array[] = $counter; } return $array; } ?> Jul 2012 Jan 2013 © 2012 UPES
  • 13. PHP Variable Scopes  The scope of a variable is the part of the script where the variable can be referenced/used.  PHP has four different variable scopes:  local  global  static  parameter Jul 2012 Jan 2013 © 2012 UPES
  • 14. Functions and variable scope  The scope of a variable defined inside a function is local by default, meaning that it has no connection with the meaning of any variables outside the function.  The syntax of this declaration is simply the word global, followed by a comma-delimited list of the variables that should be treated that way, with a terminating semicolon. Ex2: <?php  global $count1, $count2; $x=5; // global scope Ex1: $y=10; // global scope <?php function myTest() function myfunction() { { global $x,$y; $GLOBALS["n1"] = 10; $y=$x+$y; } } $n1 = 20; myTest(); myfunction(); echo $y; // outputs 15 ?> echo $n1; Jul 2012 Jan 2013 © 2012 UPES
  • 15. Static variables  The static keyword allows for an initial assignment, which has an effect only if the function has not been called before. The first time the variable executes initial value assigned.  The second time the function is called, it has the value it had at the end of the last execution. <?php function myTest() { static $x=0; echo $x; $x++; Output: } 012 myTest(); myTest(); myTest(); ?> Jul 2012 Jan 2013 © 2012 UPES
  • 16. Example function SayMyABCs3 () { static $count = 0; //assignment only if first time called $limit = $count + 10; while ($count < $limit) { print(chr(ord(‘A’) + $count)); // chr () converts ASCII to char ord() returns ASCII value of char $count = $count + 1; Output: } ABCDEFGHIJ print(“<BR>Now I know $count letters<BR>”); Now I know 10 letters } Now I’ve made 1 function call(s). $count = 0; KLMNOPQRST SayMyABCs3(); Now I know 20 letters $count = $count + 1; Now I’ve made 2 function call(s). print(“Now I’ve made $count function call(s).<BR>”); SayMyABCs3(); $count = $count + 1; print(“Now I’ve made $count function call(s).<BR>”); Jul 2012 Jan 2013 © 2012 UPES
  • 17. Parameter Scope  A parameter is a local variable whose value is passed to the function by the calling code.  Parameters are declared in a parameter list as part of the function declaration:  <?php function myTest($x) { echo $x; } myTest(5); ?> Jul 2012 Jan 2013 © 2012 UPES
  • 18. Include and require  It’s very common to want to use the same set of functions across a set of web site pages, and the usual way to handle this is with either include or require, both of which import the contents of some other file into the file being executed. Using either one of these forms is vastly preferable to cloning your function definitions (that is, repeating them at the beginning of each page that uses them).  For example, at the top of a PHP code file we might have lines like: include “basic-functions.inc”; include “advanced-function.inc”;  Both include and require have the effect of splicing in the contents of their file into the PHP code at the point that they are called. The only difference between them is how they fail if the file cannot be found. The include construct will cause a warning to be printed, but processing of the script will continue; require, on the other hand, will cause a fatal error if the file cannot be found. Jul 2012 Jan 2013 © 2012 UPES
  • 19.  include "header.php"; - Pull the file in here  include_once "header.php"; - Pull the file in here unless it has already been pulled in before  require "header.php"; - Pull in the file here and die if it is missing  require_once "header.php"; - You can guess what this means...  These can look like functions - require_once("header.php"); Jul 2012 Jan 2013 © 2012 UPES
  • 20. Missing functions  Sometimes depending on the version or configuration of a particular PHP instance, some functions may be missing. We can check that. if (function_exists("array_combine")) { echo "Function exists";} else { echo "Function does not exist";} Jul 2012 Jan 2013 © 2012 UPES
  • 21. Variable functions In PHP we can assign variable value as a function name. <?php $function_variable = "red"; $function_variable(); $function_variable = "white"; $function_variable("In white() now"); function red() { echo "In red() now"; } function white($argument) { echo $argument; } Jul 2012 Jan 2013 © 2012 UPES ?>
  • 22. Nested functions <?php or <?php outer_function(); outer_function(); function outer_function() { inner_function(); echo "Outer function"; function outer_function() inner_function(); } { function inner_function() { echo "Outer function"; echo "inner function"; function inner_function() } ?> { echo "inner function"; } } ?> Jul 2012 Jan 2013 © 2012 UPES
  • 23. Passing Variable Number of Arguments  func_num_args – Returns the number of arguments passed  func_get_arg – Returns a single argument  func_get_args – Returns all arguments in an array <?php connector('How','are','things'); function connector() { $data = ''; $arguments = func_get_args(); for ($loop_index = 0; $loop_index <func_num_args(); $loop_index++) $data .= $arguments[$loop_index] . ' '; echo $data; output: } How are things ?> Jul 2012 © 2012 UPES Jan 2013
  • 24. Jul 2012 Jan 2013 © 2012 UPES