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
Ad

More Related Content

What's hot (20)

Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
Php session
Php sessionPhp session
Php session
argusacademy
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
Shweta A
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
Jamshid Hashimi
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to html
vikasgaur31
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
HTML-(workshop)7557.pptx
HTML-(workshop)7557.pptxHTML-(workshop)7557.pptx
HTML-(workshop)7557.pptx
Raja980775
 
Html ppt
Html pptHtml ppt
Html ppt
santosh lamba
 
Html presentation
Html presentationHtml presentation
Html presentation
Amber Bhaumik
 
Php forms
Php formsPhp forms
Php forms
Anne Lee
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
Manish Bothra
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Sessions in php
Sessions in php Sessions in php
Sessions in php
Mudasir Syed
 
Javascript
JavascriptJavascript
Javascript
Nagarajan
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
Maruf Abdullah (Rion)
 
HTML
HTMLHTML
HTML
CHANDERPRABHU JAIN COLLEGE OF HIGHER STUDIES & SCHOOL OF LAW
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 

Similar to PHP Unit 3 functions_in_php_2 (20)

Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen Poreya
 
Refactoring
RefactoringRefactoring
Refactoring
Amir Barylko
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptx
Japneet9
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Php
PhpPhp
Php
Yoga Raja
 
Php introduction
Php introductionPhp introduction
Php introduction
Pratik Patel
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
Chris Chubb
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
Acácio Oliveira
 
Creating native apps with WordPress
Creating native apps with WordPressCreating native apps with WordPress
Creating native apps with WordPress
Marko Heijnen
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
adityathote3
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structures
sana mateen
 
OOP
OOPOOP
OOP
thinkphp
 
Lecture06
Lecture06Lecture06
Lecture06
elearning_portal
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen Poreya
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
Expressions and Operators.pptx
Expressions and Operators.pptxExpressions and Operators.pptx
Expressions and Operators.pptx
Japneet9
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
Chris Chubb
 
Creating native apps with WordPress
Creating native apps with WordPressCreating native apps with WordPress
Creating native apps with WordPress
Marko Heijnen
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structures
sana mateen
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
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