Lesson 05
Lesson 05
2
1. PHP Built-in Functions
• A function is a self-contained block of code that performs a
  specific task.
• PHP has a huge collection of internal or built-in functions
  that you can call directly within your PHP scripts to perform
  a specific task, like gettype(), print_r(),
  var_dump, etc.
• Few of built-in functions are listed next.
                                                              3
PHP Date and Time Functions
      Operator                                                Name
      checkdate()        Validates a Gregorian date
      date_add()         Adds an amount of days, months, years, hours, minutes & seconds to a date
 date_create_from_for
                         Returns a new DateTime object formatted according to the specified format
         mat()
     date_create()       Returns new DateTime object
    date_date_set()      Sets a new date
       date_diff()       Returns the difference between two dates
     date_format()       Returns a date formatted according to a specified format
 date_interval_create_
                         Sets up a DateInterval from the relative parts of the string
  from_date_string()
     date_modify()    Modifies the timestamp
     date_parse()     Returns associative array with detailed info about a specified date
                      Subtracts an amount of days, months, years, hours, minutes and seconds
      date_sub()      from a date
    date_time_set()   Sets the time
 date_timestamp_get() Returns the Unix timestamp representing the date
 date_timestamp_set() Sets the date and time based on an Unix timestamp
         date()       Formats a local date and time
       getdate()      Returns date/time information of the timestamp or the current local date/time
    gettimeofday()    Returns the current time
        idate()       Formats a local time/date as integer
      localtime()     Returns the local time
         time()       Returns the current time as a Unix timestamp
                                                                                               4
 timezone_name_get() Returns the name of the timezone
2. PHP User-defined Functions
• In addition to the built-in functions, PHP also allows you to define
  your own functions.
• It is a way to create reusable code packages that perform specific
  tasks and can be kept and maintained separately form main
  program.
• Here are some advantages of using functions:
    • Functions reduces the repetition of code within a program - Function
      allows you to extract commonly used block of code into a single component.
    • Functions makes the code much easier to maintain - Since a function
      created once can be used many times, any changes made inside a function
      automatically implemented at all the places without touching several files.
    • Functions makes it easier to eliminate the errors - When the program is
      subdivided into functions, if any error occur you know exactly what function
      causing the error and where to find it.
    • Functions can be reused in other application - Because a function is
      separated from the rest of the script, it's easy to reuse the same function in
      other applications.
                                                                                 5
Creating and Invoking Functions
• The basic syntax of creating a custom function can be give with:
     function functionName(){
         // Code to be executed
     }
// Calling function
getSum(10, 20);
?>
                                                             8
Functions with Optional Parameters and Default Values
• PHP allows to create functions with optional parameters — just
  insert the parameter name, followed by an equals (=) sign,
  followed by a default value, like this.
     <?php
     // Defining function
     function customFont($font, $size=1.5){
         echo "<p style=\"font-family: $font; font-size: {$size}em;
     \">Hello, world!</p>";
     }
     // Calling function
     customFont("Arial", 2);
     customFont("Times", 3);
     customFont("Courier");
     ?>
• The third call to customFont() doesn't include the second
  argument. This causes PHP engine to use the default value for the
  $size parameter which is 1.5.
                                                                      9
Returning Values from a Function
• A function can return a value back to the script that
  called the function using the return statement. The
  value may be of any type, including arrays and objects.
      <?php
      // Defining function
      function getSum($num1, $num2){
          $total = $num1 + $num2;
          return $total;
      }
                                                       10
Passing Arguments to a Function
• In PHP there are two ways you can pass arguments to a function:
     • By value - By default, function arguments are passed by value so that if the
       value of the argument within the function is changed, it does not get affected
       outside the function.
     • By reference - To allow a function to modify its arguments, they must be
       passed by reference. Passing an argument by reference is done by
       prepending an ampersand (&) to the argument name in the function
       definition, as shown in the example below:
           <?php
           /* Defining a function that multiply a number
           by itself and return the new value */
           function selfMultiply(&$number){
               $number *= $number;
               return $number;
           }
           $mynum = 5;
           echo $mynum; // Outputs: 5
           selfMultiply($mynum);
           echo $mynum; // Outputs: 25
           ?>
                                                                                  11
Understanding the Variable Scope
• Variables can be declared anywhere in a PHP script.
• But, the location of the declaration determines the extent of a
  variable's visibility within the PHP program i.e. where the variable can
  be used or accessed. This accessibility is known as variable scope.
• By default, variables declared within a function are local and they
  cannot be viewed or manipulated from outside of that function, as
  demonstrated in the example below:
      <?php
      // Defining function
      function test(){
          $greet = "Hello World!";
          echo $greet;
      }
                                                                       12
Understanding the Variable Scope
• Similarly, if you try to access or import an outside variable inside the
  function, you'll get an undefined variable error, as shown in the following
  example:
      <?php
      $greet = "Hello World!";
      // Defining function
      function test(){
          echo $greet;
      }
      // Defining function
      function test(){
          global $greet;
          echo $greet;
      }
                                                                               14
Part 2: PHP Control Structures
                                 15
PHP Conditional Statements
• PHP allows you to write code that perform different
  actions based on the results of a logical or comparative
  test conditions at run time.
• This means, you can create test conditions in the form of
  expressions that evaluates to either true or false and
  based on these results you can perform certain actions.
• There are several statements in PHP that you can use to
  make decisions:
       - The if statement
       - The if...else statement
       - The if...elseif....else statement
       - The switch...case statement
                                                         16
The if Statement
• The if statement is used to execute a block of code only
  if the specified condition evaluates to true. This is the
  simplest PHP's conditional statements and can be
  written like:
      if(condition){
          // Code to be executed
      }
• The following example will output "Have a nice weekend!" if the current day
  is Friday, and "Have a nice Sunday!" if the current day is Sunday, otherwise
  it will output "Have a nice day!"
         <?php
         $d = date("D");
         if($d == "Fri"){
             echo "Have a nice weekend!";
         } elseif($d == "Sun"){
             echo "Have a nice Sunday!";
         } else{
             echo "Have a nice day!";
         }
         ?>
                                                                                        19
The Ternary Operator
• The ternary operator provides a shorthand way of writing the
  if...else statements. It is represented by the question mark (?)
  symbol and it takes three operands:
    • a condition to check
    • a result for true
    • a result for false
       <?php
       if($age < 18){
           echo 'Child'; // Display Child if age is less than 18
       } else{
           echo 'Adult'; // Display Adult if age is greater than or equal to
       18
       }
       ?>
                                                                           22
Example - Switch…Case Statements
          <?php
          $today = date("D");
          switch($today){
              case "Mon":
                  echo "Today is Monday. Clean your house.";
                  break;
              case "Tue":
                  echo "Today is Tuesday. Buy some food.";
                  break;
              case "Wed":
                  echo "Today is Wednesday. Visit a doctor.";
                  break;
              case "Thu":
                  echo "Today is Thursday. Repair your car.";
                  break;
              case "Fri":
                  echo "Today is Friday. Party tonight.";
                  break;
              case "Sat":
                  echo "Today is Saturday. Its movie time.";
                  break;
              case "Sun":
                  echo "Today is Sunday. Do some rest.";
                  break;
              default:
                  echo "No information available for that day.";
                  break;
          }
          ?>
• The switch-case statement differs from the if-elseif-else statement in one important way. The
  switch statement executes line by line (i.e. statement by statement) and once PHP finds a
  case statement that evaluates to true, it's not only executes the code corresponding to that
  case statement, but also executes all the subsequent case statements till the end of the
  switch block automatically.
• To prevent this add a break statement to the end of each case block.                         23
Part 3: PHP Iterative Structures
                                   24
PHP Loops
• Loops are used to execute the same block of code
  again and again, until a certain condition is met.
• The basic idea behind a loop is to automate the
  repetitive tasks within a program to save the time and
  effort.
• PHP supports four different types of loops.
 - while - loops through a block of code until the condition is evaluate
   to true
 - do…while - the block of code executed once and then condition is
   evaluated. If the condition is true the statement is repeated as long
   as the specified condition is true.
 - for - loops through a block of code until the counter reaches a
   specified number.
 - foreach - loops through a block of code for each element in an array
                                                                     25
PHP while Loop
• The while statement will loops through a block of code
  until the condition in the while statement evaluate to true.
       while(condition){
           // Code to be executed
       }
• The example below define a loop that starts with $i=1. The
  loop will continue to run as long as $i is less than or equal
  to 3. The $i will increase by 1 each time the loop runs:
       <?php
       $i = 1;
       while($i <= 3){
           $i++;
           echo "The number is " . $i . "<br>";
       }
       ?>
                                                             26
PHP do…while Loop
• The do-while loop is a variant of while loop, which evaluates the condition
  at the end of each loop iteration.
• With a do-while loop the block of code executed once, and then the
  condition is evaluated, if the condition is true, the statement is repeated as
  long as the specified condition evaluated to is true.
        do{
              // Code to be executed
        }
        while(condition);
• The following example define a loop that starts with $i=1. It will then
  increase $i with 1, and print the output. Then the condition is evaluated, and
  the loop will continue to run as long as $i is less than, or equal to 3.
        <?php
        $i = 1;
        do{
            $i++;
            echo "The number is " . $i . "<br>";
        }
        while($i <= 3);
        ?>
                                                                             27
Difference Between while and do…while Loop
• The while loop differs from the do-while loop in one
  important way,
   •    with a while loop, the condition to be evaluated is
       tested at the beginning of each loop iteration, so if
       the conditional expression evaluates to false, the
       loop will never be executed.
   • With a do-while loop, on the other hand, the loop
     will always be executed once, even if the conditional
     expression is false, because the condition is
     evaluated at the end of the loop iteration rather than
     the beginning.
                                                               28
PHP for Loop
• The for loop repeats a block of code until a certain condition is met. It
  is typically used to execute a block of code for certain number of times.
        for(initialization; condition; increment){
            // Code to be executed
        }
                                                        30
PHP foreach Loop
• There is one more syntax of foreach loop, which is
  extension of the first.
      foreach($array as $key => $value){
          // Code to be executed
      }
      <?php
      $superhero = array(
          "name" => "Peter Parker",
          "email" => "peterparker@mail.com",
          "age" => 18
      );
                      32
PHP Classes
• A class is a self-contained, independent collection of
  variables and functions which work together to perform one
  or more specific tasks, while objects are individual instances
  of a class.
• A class acts as a template or blueprint from which lots of
  individual objects can be created.
• For example, think of a class as a blueprint for a house. The
  blueprint itself is not a house, but is a detailed plan of the
  house. While, an object is like an actual house built
  according to that blueprint. We can build several identical
  houses from the same blueprint, but each house may have
  different paints, interiors and families inside.
                                                              33
PHP Classes
• A class can be declared using the class keyword, followed by the name of the
  class and a pair of curly braces ({}), as shown in the following example.
• Create a PHP file named Rectangle.php with the following example code.
          <?php
          class Rectangle
          {
              // Declare properties
              public $length = 0;
              public $width = 0;
                                                                           34
Part 5: Arrays and associated
          operations
                                35
PHP Array Functions
    Operator                                            Name
       array()      Create an array
  array_column()    Return the values from a single column in the input array
   array_filter()   Filters elements of an array using a user-defined function
   array_keys()     Return all the keys or a subset of the keys of an array
   array_map()      Sends the elements of the given arrays to a user-defined function
    array_pop()     Removes and return the last element of an array
   array_push()     Inserts one or more elements to the end of an array
  array_replace()   Replaces the values of the first array with the values from following arrays
  array_reverse()   Return an array with elements in reverse order
  array_search()    Searches an array for a given value and returns the corresponding key
   array_sum()      Calculate the sum of values in an array
  array_unique()    Removes duplicate values from an array
  array_values()    Return all the values of an array
       count()      Count all elements in an array
      current()     Return the current element in an array
       each()       Return the current key and value pair from an array and advance the array cursor
     in_array()     Checks if a value exists in an array
        list()      Assign variables as if they were an array
      sizeof()      Count all elements in an array
        sort()      Sort an array in ascending order                                             36
PHP Arrays
• A PHP array is a variable that stores more than one piece of
  related data in a single variable.
• Think of an array as a box of chocolates with slots inside.
• The box represents the array itself while the spaces
  containing chocolates represent the values stored in the
  arrays.
           1   2   3                             Array
Array values
                                                            37
PHP Numeric Arrays
• Numeric arrays use number as access keys.
• An access key is a reference to a memory slot in an array
  variable.
• The access key is used whenever we want to read or assign
  a new value an array element.
         <?php
         $variable_name[n] = value;
         ?>
               Or
         <?php
         $variable_name = array(n => value, …);
         ?>
HERE,
 • “$variable_name…” is the name of the variable
 • “[n]” is the access index number of the element
 • “value” is the value assigned to the array element.
                                                          38
PHP Numeric Arrays - Example
<?php
$movie[0] = "Shaolin Monk";
$movie[1] = "Drunken Master";
$movie[2] = "American Ninja";
$movie[3] = "Once upon a time in China";
$movie[4] = "Replacement Killers";
echo $movie[3];
$movie[3] = " Eastern Condors";
echo $movie[3];
?>
Output:
  Once upon a time in China Eastern Condors
<?php
$movie = array(0 => “Shaolin Monk”,
           1 => "Drunken Master”,
           2 => "American Ninja”,
           3 => "Once upon a time in China”,
           4 => "Replacement Killers”);
?>
                                               39
Loop through a Numeric Array/Indexed Array
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
Output:
  Volvo
  BMW
  Toyota
                                           40
PHP Associative Arrays
• Associative array differ from numeric array in the sense that
  associative arrays use descriptive names for id keys.
        <?php
        $variable_name[‘key_name’] = value;
        ?>
             Or
        <?php
        $variable_name = array(keyname => value, …);
        ?>
HERE,
 • “$variable_name…” is the name of the variable
 • “[key_name]” is the access index number of the element
 • “value” is the value assigned to the array element.
                                                              41
PHP Associative Arrays - Example
<?php
$persons = array("Mary" => "Female",
         "John" => "Male",
         "Mirriam" => “Female");
echo($persons);
echo “";
echo "Mary is a " . $persons["Mary"];
?>
Output:
  Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female
                                                                                   42
Loop through an Associative Array
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Output:
  Key=Peter, Value=35
  Key=Ben, Value=37
  Key=Joe, Value=43
                                                         43
PHP Multi-dimensional Arrays
• These are arrays that contain other nested arrays.
• The advantage of multidimensional arrays is that they allow
  us to group related data together.
<?php
$movies array(
"comedy" => array("Pink Panther", "John English", "The Spy"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"romance" => array("Romeo and Juliet”)
);
print_r($movies);
?>
Output:
Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => The
spy ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array
( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )
                                                                                44
PHP Multi-dimensional Arrays
• Another way to define the same array is as follows
<?php
$movies array(
       "comedy" => array(
               0 => "Pink Panther",
               1 => "John English",
               2 => "The Spy”
               ),
       "action" => array(
               0 => "Die Hard",
               1 => "Expendables"
               ),
       "epic" => array(
               0 => "The Lord of the rings”
               ),
       "romance" => array(
               0 => "Romeo and Juliet”
               )
);
echo $movies[“comedy”][0];
?>
Output:
  Pink Panther
                                                       45
Viewing Array Structure and Values
• The structure and values of any array can be viewed by using one of two
  statements — var_dump() or print_r().
• The print_r() statement, however, gives somewhat less information.
          <?php
          // Define array
          $cities = array("London", "Paris", "New York");
          <?php
          // Define array
          $cities = array("London", "Paris", "New York");
                                 47
PHP String Functions
   Operator                                            Name
       chr()       Returns a one-character string containing the character specified by ASCII
  chunk_split()    Split a string into smaller chunks
      echo()       Output one or more strings
     fprintf()     Write a formatted string to a specified output stream
       join()      Return a string by joining the elements of an array with a specified string
       ord()       Returns the ASCII value of the first character of a string
       print()     Output a string
      printf()     Output a formatted string
     sprintf()     Return a formatted string
   str_repeat()    Repeats a string a specified number of times
  str_replace()    Replace all occurrences of the search string with the replacement string
    str_split()    Splits a string into an array
str_word_count()   Counts the number of words in a string
     strcmp()      Binary safe comparison of two string (case sensitive)
      strlen()     Returns the length of a string
   strtolower()    Converts a string to lowercase
   strtoupper()    Converts a string to uppercase
     substr()      Return a part of a string
       trim()      Removes whitespace (or other characters) from the beginning and end of a string
                                                                                              48
PHP String Functions
Creating Strings Using Single quotes
    <?php
       var_dump(“You need to be logged in to view this page”);
    ?>
Output:
    string(42) "You need to be logged in to view this page"
50