Upgrade to Pro — share decks privately, control downloads, hide ads and more …

2. Functions & Loops

2. Functions & Loops

An in-depth look at the numerous types of functions, statements and loops in PHP.

Ben Major

March 17, 2016

Transcript

30 slides
  1. Course Overview 1. PHP Overview & Basics 2. Functions 3.

    Loops 4. MySQL and data-rich websites 5. Security and Good Practice 6. Working with JSON, XML and APIs 7. Object-Oriented PHP Development 8. Conclusion
  2. Functions 101 • Functions allow us to write re-usable code

    snippets which perform actions. • Defined using the function keyword, followed by the function name: • Function code should be wrapped in curly braces ({}), and can accept a number of parameters, which are passed into the function after the call: • function  my_function(  $var1,  $param2,  …  )
 {
      //  Your  function  code  here.  
      //  This  function  is  called  my_function.
 }
  3. Functions 102 • Function names must be unique, and we

    cannot redefine functions or use system function names. • This will trigger a parse error: • function  strtolower()
 {
        //  Some  function  code.
 }   • We can check if a function name is already defined using the function_exists(‘strtolower’) function. • We pass the name of the function as a string • If the function name already exists, returns true. Otherwise, returns false.
  4. Functions 103 • Functions should be as reusable as possible.

    • We can echo out things within a function, but it’s much better to return them instead! • function  get_name(  $name  )  {  echo  $name;  }   • function  get_name(  $name  )  {  return  $name;  }
 echo  get_name(  ‘Ben’  );
  5. Functions 104 • Functions are affected by variable scope. •

    Things functions CAN access: • Other functions • Function parameters • Variables defined as global   • Things functions CANNOT access: • Variables defined outside of the function (unless we declare them as global).
  6. //  Define  a  variable:
 $myVar  =  ‘a  string’;
 
 function

     my_function(  $param1  )
 {
        echo  $myVar;    //  Won’t  output  anything  because  $myVar  is  out  of  scope
        echo  $param1;  //  Will  output  OK,  because  $param1  is  a  parameter.
 
        echo  strtolower(  $param1  );    //  Outputs  OK.
 
        global  $myVar;
        echo  $myVar;    //  Now  outputs,  because  $myVar  is  a  global  var.  
 }

  7. Functions 105 • We can make function parameters optional by

    giving them a value in the function definition. • If we don’t assign a value to the parameter, it will be required: • function  my_function(  $param1  =  ‘string’  )  {    }
 my_function();                        //  Valid  function  call,  $param1  assumes  
                                                    //  ‘string’
 my_function(  ‘another’  );  //  Also  valid,  $param1  is  override  
                                                    //  with  ‘another’   • function  my_function(  $param1  )  {    }
 my_function();                      //  Throws  error,  empty  parameter.
 my_function(  ‘string’  );  //  Valid  -­‐  $param1  =  ‘string’
  8. Functions 106 • When we pass a variable to a

    function, it creates a duplicate, locally-scoped variable. • Sometimes, we want the function to modify the original variable that we passed as a parameter. • We can achieve this using pass by reference. • When we pass a variable to a function by reference, we are passing a pointer to the original variable, and it will be modified. • To define a by reference variable, we append the & literal in the parameter list.
  9. //  Define  a  variable:
 $myVar  =  ‘a  string’;
 
 function

     my_function(  &$param1  )
 {
        //  $param1  is  an  alias  of  $myVar,  instead  of  a  copy  of  it.
        $param1.=  ‘  appended’;
 
        //  $myVar  now  =  ‘a  string  appended’;
 }

  10. If / Elseif / Else • if() statements allow us

    to check the value of something, and execute code based on its state. • If the statement returns true, the code is executed. If it is false, it is not. • elseif() allows us to specify what should happen if the initial if() returns false, but we need to check a second condition. These may be used ad infinitum. • else will be executed if all of the above statements have returned false.
  11. //  Define  a  variable:
 $bool1  =  false;
 $bool2  =  true;


    
 if(  $bool1  ==  true  )
 {
        //  Won’t  execute,  because  $bool1  ==  false.
 }
 
 else  if(  $bool2  )
 {
        //  Will  execute,  because  $bool2  ==  false.
 }
 
 else
 {
        //  Will  never  execute,  because  the  elseif  has  executed.
 }
  12. • We can combine clauses in an if() statement using

    bitwise comparison: • if(  $myVar  &  $myVar2  )  {    }   • if(  $myVar  &&  $myVar2  )  {    }   • if(  $myVar  |  $myVar2  )  {    }   • if(  $myVar  ||  $myVar2  )  {    }
  13. • We can use if() statements to check the value

    of something. • We need to be careful of using the correct operators: • == - equality operator. • === - precise equality operator. • $myVar  =  ‘value’;
 if(  ‘value’  ==  $myVar  )  {    }
 if(  $myVar  ==  ‘value’  )  {    }   • $myVar  =  (int)  123;
 if(  ‘123’  ==  $myVar  )  {    }    //  Executes,  because  of  loose-­‐typing
 if(  ‘123’  ===  $myVar  )  {    }  //  Does  not  execute,  type  mismatch
  14. Operators • Equality operators: • if(  $foo  ==    ‘1’

     )
 if(  $foo  ===  ‘1’  )
 if(  $foo  !=    ‘1’  )
 if(  $foo  !==  ‘1’  )   • Comparison operators: • if(  $foo  >    1  )
 if(  $foo  >=  1  )
 if(  $foo  <    1  )
 if(  $foo  <=  1  )
 if(  $foo  <>  1  )    //  This  is  the  same  as  writing  $foo  !=  1
  15. Ternary Operator • Technically a language struct, but included here

    for completeness. • Allows us to assign a value to a variable based on a condition (or several conditions). • Weird syntax, but remember it: • $foo  =  ($bar  ==  1)  ?  ‘bar  is  1’  :  ‘bar  is  not  1’;   • if(  $bar  ==  1  )
 {
        $foo  =  ‘bar  is  1’;
 }
 else
 {
        $foo  =  ‘bar  is  not  1’;
 }
  16. Switch Statements • Switch statements allow us to check something

    for multiple values. • Much cleaner than than writing if()  elseif()  elseif()  else blocks. • Each possibility exists as a case. • We can also define a default case, to be used when no other matches were found. • Cases can be combined to use the same code in two or more cases.
  17. //  Define  a  variable:
 $myVar  =  ‘some  string’;
 
 switch(

     $myVar  )
 {
        case  ‘some  string’:
                //  Some  code  in  here.
                break;
 
        case  ‘another  value’:
                //  Some  other  code  in  here.
                break;
 
        case  ‘final  value’:
        default:  
                //  Some  more  code.
                break;
 }
  18. For Loop • for() loops allow us to loop through

    x iterations of something. • If we wanted to run something 10 times, for example: • for(  $i  =  0;  $i  <  10;  $i++  )
 {
        //  $i  will  increment  by  1  each  time.
        //  Any  code  we  put  in  here  will  be  executed  each
        //  iteration.
 }   • We don’t have to use $i - it’s just short and clean; the incremental variable can be called anything (that isn’t already defined).
  19. For Loop • If we need to combine for() loops,

    we need to use a different iteration variable: • for(  $i  =  0;  $i  <  10;  $i++  )
 {
        for(  $j  =  0;  $j  <  10;  $j++  )
        {
 
        }
 }   • After the above has run, $i  ==  10 and $j  ==  10! • We can reset them using $i  =  0;
  20. Foreach Loop • foreach() loops allow us to loop over

    arrays very easily. • Can be used with 0-indexed and associative arrays. • Useful when we don’t know the length of an array, or if the array has distinct keys.
  21. //  Define  an  array:
 $myArray  =  array(  ‘foo’,  ‘bar’,  ‘hello’,

     ‘world’  );
 
 foreach(  $myArray  as  $value  )
 {
        //  $value  will  be  recursively  set  to:
        //  ‘foo’
        //  ‘bar’
        //  ‘hello’
        //  ‘world’
 }
  22. //  Define  an  array:
 $myArray  =  array(  
    

       ‘foo’          =>  ‘bar’,
        ’hello’      =>  ‘world’,
        ‘another’  =>  ‘value’
 );
 
 foreach(  $myArray  as  $key  =>  $value  )
 {
        //  $key  will  hold  the  array  key  for  this  iteration
        //  $value  will  hold  the  value  for  this  iteration
 }
  23. While Loop • while() loops allow us to execute code

    while a certain condition is truthy. • Useful for looping through when we’re changing a value dynamically. • Very useful when working with databases and looping over object properties (more later on this).
  24. //  Define  our  condition:
 $myFlag  =  true;
 
 while(  $myFlag

     )
 {
        //  Do  something  while  $myFlag  ==  true;
        
        //  If  we  have  set  $myFlag  to  false  inside  here,
        //  The  loop  no  longer  executes.
 }
  25. Do While Loop • do  while() loops allow us to

    execute code while a certain condition is truthy, executing it at least once. • It will execute the code defined before assessing the condition’s state. • Useful if your loop needs to execute at least once, regardless of the condition’s state. • for example, incrementing a user’s age by 1 every year until they’re 100).
  26. //  Define  our  condition:
 $myFlag  =  true;
 
 do
 {


    
        //  This  code  is  executed  once.
        //  Then,  $myFlag  is  evaluated.  If  it’s  true,  the  code  
        //  executes  again,  and  keeps  going  until  $myFlag  ==  false.
 
 }  while(  $myFlag  );
  27. Tasks 1. Write a function which returns an array of

    month names in English 2. Write a function which returns a <select> element of month names, with the following options: • We can pass the following attributes as parameters to the function, and they are respected in the generated markup: 
 id, class, name   • The <option> elements display the month’s name, but their value is equal to its numerical index (i.e. January = 1, February = 2, etc.)

More Decks by Ben Major

Other Decks in Education