Enter your Sign on user name and password.

Forgot password?
  • Follow us on:

Professor Matthew M. is Educator's instructor for the Introduction to PHP course. As a self-taught PHP developer, Matthew understands first-hand the difficulties encountered by newcomers to PHP. He focuses on the topics most relevant to web developers looking to build their skill set by learning to add dynamic content and advanced functionality to their websites. Matthew focuses his lessons on actual code and builds on a web application using new skills learned throughout the series. Topics covered include setting up the development environment, arrays, type casting, user-defined functions, and loops. Downloadable code and homework solutions are included so students can follow along with the lessons.

Loading video...
expand all   collapse all
I. Introduction to PHP
  Course Introduction 12:13
   Intro 0:00 
   What Is PHP? 0:12 
    PHP Hypertext Preprocessor 0:13 
   Why Learn PHP? 1:09 
    Why Learn PHP? 1:10 
   Web Application: Educator Store 2:25 
    Web Application: Educator Store 2:26 
    Example of Web Application 3:18 
   PHP in the Educator Store 7:12 
    Dynamic Content Generation 7:22 
    Ease of Website Maintenance 7:55 
    Form Input Processing and Access to Advanced Functionality 9:00 
   What You Will Learn 9:36 
    What You Will Learn 9:37 
   Who Is This Course For? 10:56 
    Who Is This Course For? 10:57 
  How PHP & The Web Work 15:32
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   Client-Server Model 0:53 
    Client-Server Model 0:54 
   HTTP Protocol 2:15 
    Definition of Protocol 2:16 
    Hypertext Transfer Protocol (HTTP) 2:37 
   Uniform Resource Locators 3:46 
    Uniform Resource Locators (URLs) 3:47 
    Form of URLs 4:13 
    Accessing Webpages with URLs 5:13 
   Serving Webpages 6:14 
    Serving Webpages, Client Machine, and Server Machine 6:15 
   Static vs. Dynamic Webpages 8:30 
    Static Webpage 8:31 
    Dynamic Webpage 8:55 
   Server-Side Scripting 9:54 
    Server-Side Scripting 9:55 
   Static and Dynamic Webpage Coding Example 11:17 
    Static and Dynamic Webpage Coding Example 11:18 
   Serving Dynamic Webpages 13:07 
    Serving Dynamic Webpages 13:08 
  Setting Up Your Development Environment 33:11
   Intro 0:00 
   Lesson Overview 0:08 
    Lesson Overview 0:09 
   Development Environments 1:04 
    Development Environments 1:05 
    Our Default Development Environment: Window 7 1:54 
   Remote Development 4:04 
    Development Machine & Remote Server 4:05 
   Local Development 6:54 
    Development Machine 6:55 
   Software Used In This Course 9:41 
    Firefox Web Browser & Firebug Add-On 9:42 
    XAMPP 12:15 
    PSPAD Text Editor 13:16 
   XAMPP Installation 13:49 
    XAMPP Installation 13:50 
   Verify XAMPP Install 16:26 
    Verify XAMPP Install 16:27 
   localhost 19:08 
    localhost and 127.0.0.1 'loopback' IP Address 19:09 
   Document Root 21:16 
    Document Root and Directory Name 21:17 
    Document Root for Apache in XAMPP: htdocs & Example 22:13 
   Text Editor Spectrum 26:12 
    Text Editor Spectrum: Barebones to IDE 26:13 
    PSPad & Example 27:02 
   Finding Help 30:26 
    Web Resources 30:27 
   Homework Challenge 31:36 
    Homework Challenge 31:37 
   Homework Challenge (cont.) 32:38 
    Homework Challenge (cont.) 32:39 
  Your First PHP Script 12:41
   Intro 0:00 
   Lesson Overview 0:19 
    Lesson Overview 0:20 
   .php To HTML 1:00 
    .php To HTML 1:01 
   PHP Delimiters 2:20 
    PHP Delimiters: Opening & Closing PHP Tags 2:21 
   'Hello, World!' Example 4:34 
    Echo Statement & PHP Tags 4:35 
    Adding Second Heading 7:34 
   Homework Challenge 9:56 
    Homework Challenge 9:57 
  Basic PHP Syntax 40:24
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   PHP Delimiters 0:38 
    Long and Script Form 0:39 
    Short and ASP Style 1:33 
    Example 2:01 
   php.ini: PHP's Configuration 3:40 
    php.ini 3:41 
    Configuration Directives 3:48 
    Short and ASP Style: Enabled/Disabled 4:13 
    phpinfo() 7:58 
   Statements 14:28 
    PHP Statements 14:29 
    Example: PHP Statements 14:55 
   Comments 16:53 
    PHP Comments 16:55 
    Single-line Comments 17:37 
    Multi-line Comments 18:13 
    Example: PHP Comments 18:47 
   Coding Conventions 24:26 
    Coding Conventions 24:27 
    Example: PHP Coding Conventions 26:19 
   Homework Challenge #1 33:51 
    Homework Challenge #1 33:52 
   Homework Challenge #1 (cont.) 35:41 
    Homework Challenge #1 (cont.) 35:42 
   Homework Challenge #2 36:09 
    Homework Challenge #2 36:10 
   Homework Challenge #2 (cont.) 38:07 
    Homework Challenge #2 (cont.) 38:08 
  Variables & Numeric Data Types 16:38
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:12 
   Working With Data 0:48 
    8 Types of Data for PHP 0:49 
   Identifiers 1:40 
    Identifiers: Definition and Example 1:41 
   Variables 2:47 
    Variables Definition 2:48 
    Variables Syntax 3:06 
   Integer Data Type 4:44 
    Integer Data Type 4:45 
    Integer Literals 5:08 
    Examples 5:30 
   Float Data Type 6:26 
    Float Data Type 6:27 
    Float Literals 7:00 
    Example 7:21 
   Example: PHP Code Declaring Variables 8:06 
    Example: PHP Code Declaring Variables 8:07 
   var_dump() Function 9:59 
    var_dump() 10:00 
    Example: Code and Output 10:30 
    Example: var_dump() Function 11:19 
   Coding Conventions: Variables 12:32 
    Lower Camel Case Notation 12:33 
    Variable Name Lengths 13:54 
   Homework Challenge 14:54 
    Homework Challenge 14:55 
  String Data Type 18:06
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   String Data Type 0:29 
    String Data Type 0:30 
    Specifying String Literals 1:03 
   Single-Quoted Strings 1:53 
    Single-Quoted Strings 1:54 
   Escape Sequences 2:31 
    Escape Sequences 2:32 
    Example 2:46 
    Escape Sequences for Commonly Used Special Characters 4:32 
   Double-Quoted Strings 6:04 
    Double-Quoted Strings 6:05 
    Variable Interpolation 6:44 
   Coding Conventions: Strings 7:54 
    Coding Conventions: Strings 7:55 
   Homework Challenge 8:54 
    Homework Challenge 8:55 
  Include Files & Web Application Introduction 38:43
   Intro 0:00 
   Lesson Overview 0:16 
    Lesson Overview 0:17 
   include Statement 0:47 
    include Statement: Definition 0:48 
    Include Statement: Syntax 2:05 
    include Statement: Example 2:25 
   include Path 6:32 
    Absolute and Relative Path 6:34 
    Specified Path 7:15 
    Not Specified Path 7:55 
   Code Reuse 9:35 
    Code Reuse 9:36 
    Example 11:11 
   require Statement 12:56 
    require Statement: Definition 12:57 
    require Statement: Syntax 13:32 
    Include versus Require 13:52 
   Coding Conventions 16:33 
    Coding Conventions 16:34 
   Introduction to Our Web Application 20:32 
    Introduction to Our Web Application 20:33 
    Updating Web Application 21:14 
    Web Application Example 22:59 
   Homework Challenge 35:33 
    Homework Challenge 35:34 
   Homework Challenge (cont.) 37:38 
    Homework Challenge (cont.) 37:39 
  Arrays 34:00
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   What is an Array? 0:42 
    What is an Array? 0:43 
    Arrays in PHP 1:44 
    Keys and Values 2:15 
   Types of Arrays 3:37 
    Indexed Arrays & Associative Arrays 3:38 
   array() Construct 6:47 
    Declaring Arrays 6:48 
    Defining Indexed Array 7:00 
    Defining Associative Arrays 7:43 
   Square Bracket Syntax 8:50 
    Square Bracket Syntax 8:51 
    Accessing Indexed Arrays 9:02 
    Accessing Associative Arrays 9:56 
   Arrays Example 10:41 
    Indexed Arrays Example 10:45 
    Associative Arrays Example 13:55 
   Multi-Dimensional Arrays 18:28 
    Multi-Dimensional Arrays 18:29 
    Multi-Dimensional Arrays Example 18:51 
    Multi-Dimensional Arrays in PHP File 20:34 
   Coding Conventions: Arrays 27:59 
    Coding Conventions: Arrays 28:00 
   Homework Challenge #1 29:20 
    Homework Challenge #1 29:21 
   Homework Challenge #2 30:38 
    Homework Challenge #2 30:39 
  Web Application Development 27:38
   Intro 0:00 
   Versions 0:14 
    Version 3.0 1:23 
    Version 3.1 8:08 
    Version 3.2 11:42 
    Version 3.3 20:27 
   Homework Challenge 26:31 
    Homework Challenge 26:32 
  Script Input & The GET Method 30:18
   Intro 0:00 
   Lesson Overview 0:15 
    Lesson Overview 0:16 
   Providing Input to PHP 0:39 
    GET Method, POST Method, and Cookies 0:40 
    Name/Value Pairs 1:22 
   GET Method 1:57 
    HTTP GET Method 1:58 
    Query String 2:52 
   GET Method Example 3:38 
    GET Method Example 3:39 
   Review of HTML Forms 8:16 
    HTML Forms 8:17 
    Input Control and Submitted Form 9:13 
   <form> Tag 10:07 
    <form> Tag 10:08 
    Method 10:34 
    Action 11:13 
   Input Control Examples 11:50 
    Input Control Examples 11:51 
   Common Input Controls 17:31 
    Common Input Controls 17:32 
   Query Strings 18:52 
    Query Strings 18:53 
    Query Strings Syntax 19:12 
   URL Encoding 20:01 
    URL Syntax 20:02 
    Examples 21:17 
    Simple Form Example 22:28 
   urlencode() Function 24:08 
    urlencode() Function 24:09 
    Example 25:03 
   urlEncoding Text Example 25:54 
    Simple Form Example 25:55 
   Homework Challenge 28:46 
    Homework Challenge 28:47 
  Accessing Form Data in PHP 32:01
   Intro 0:00 
   Lesson Overview 0:17 
    Lesson Overview 0:18 
   $_GET Array 0:48 
    $_GET Array 0:49 
    Accessing the Value of a Name/Value Pair Submitted Via GET 1:04 
   Name Form Example 2:54 
    Name Form and the $_GET Array 2:55 
   Using Arrays with Input Controls 6:34 
    Using Arrays with Input Controls 6:35 
    Common Example 6:47 
   Indexed Array Form Example 8:16 
    Indexed Array Form Example 8:17 
   Associative Arrays with Input Controls 10:14 
    Associative Arrays with Input Controls 10:15 
   Associative Arrays Example 11:41 
    Associative Arrays Example 11:42 
   Echo Form Example 15:18 
    Echo Form Example 15:19 
   Outputting Arrays In String 23:42 
    Variable Interpolation 23:43 
    Outputting a Value in an Indexed Array Within a String 24:12 
    Simple' Syntax, 'Complex' Syntax, and 'Curly Brace' Syntax 25:00 
   Outputting Arrays In String Example 26:25 
    Outputting Arrays In String Example 26:26 
   Homework Challenge 29:39 
    Homework Challenge 29:40 
  Web Application Development 20:20
   Intro 0:00 
   Lesson Overview 0:19 
    Lesson Overview 0:20 
   Version 3.3 0:38 
    Version 3.3 0:42 
   Version 4.0 Changelog 2:43 
    GET Query 2:45 
    Adding, Editing, and Removing 3:24 
   Version 4.0 Coding Example 3:55 
    item.php, itemID, and itemListing 4:00 
   Version 4.1 Changelog 10:36 
    Version 4.1 Changelog 10:37 
   Version 4.1 Coding Example 11:45 
    Adding Checkout and Thank You & Editing Footer and Store 11:46 
   Homework Challenge 18:45 
    Homework Challenge 18:46 
  Expression & Operators 31:56
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   Expressions 0:41 
    Expressions Definition 0:42 
    Example: Literals 0:55 
    Example: Variables 1:05 
   Operators 1:44 
    Operators Definition 1:45 
    Unary, Binary, and Ternary Operators 2:07 
   Assignment Operators 2:52 
    Assignment Operators 2:53 
    Array Assignment Operator 3:47 
   Arithmetic Operators 6:15 
    Operators for Common Arithmetic Operations 6:16 
    Modulus Operator 7:41 
    Arithmetic Operators Example 8:25 
   Increment/Decrement Operators 10:48 
    Increment/Decrement Operators 10:49 
    Pre- and Post- Increment/Decrement 12:43 
    Coding Example 15:14 
   Combined Assignment Operators 16:44 
    Combined Assignment Operators 16:45 
    Combined Assignment Operators Examples 18:23 
    Coding Example 19:39 
   String Operators 20:28 
    Concatenation Operator, String Variables, and String Literals 20:29 
    String Operators Example 22:41 
   Precedence & Associativity 23:40 
    Precedence & Associativity 23:41 
    Expression Containing Multiple Operations 23:58 
    Expression Containing Two Operations of Equal Precedence 25:55 
    Using Parentheses to Force Precedence 26:52 
    Precedence & Associativity Review 28:57 
   Homework Challenge 31:08 
    Homework Challenge 31:09 
  Web Application Development 20:51
   Intro 0:00 
   Lesson Overview 0:15 
    Lesson Overview 0:16 
   Version 4.1 Review 0:33 
    Version 4.1 Review 0:34 
   Version 5.0 Changelog 1:05 
    Version 5.0 Changelog 1:06 
   Version 5.0 Example 2:19 
    Adding View Cart & Editing Checkout, Footer and Store 2:20 
   Version 5.1 Changelog 15:36 
    Version 5.1 Changelog 15:37 
   Version 5.1 Coding Example 17:33 
    Forwarding Order Total to Thank You Page 17:34 
   Homework Challenge 20:09 
    Homework Challenge 20:10 
  Boolean & Null Data Types 20:11
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Boolean Data Type 0:38 
    Boolean Data Type 0:39 
    Two Boolean Literals 1:24 
   Boolean Example 1:50 
    Boolean Example 1:51 
   Comparison Operators 4:00 
    Comparison Operators Definition 4:01 
    Common Comparison Operators 4:40 
    Comparison Operators Example 6:49 
   Comparison Operators (Cont.) 10:10 
    Identical and Not Identical 10:11 
    Example: Identical and Not Identical 11:24 
   Null Data Type 13:36 
    Null Data Type Definition 13:37 
    Null Literal 14:08 
    Variable and Null Data Type 14:30 
    '==' Operator 15:24 
    Null Data Type Example 15:59 
   Coding Convention 18:41 
    Coding Convention 18:42 
   Homework Challenge 19:17 
    Homework Challenge 19:18 
  Type Casting 22:41
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Type Juggling 0:54 
    Type Juggling 0:55 
    Automatic Conversion 2:23 
   Type Casting 3:53 
    Type Casting 3:54 
    Implicit and Explicit Type Casting 4:00 
    Explicitly 'cast' a Variable Example 4:16 
   Type Casting (cont.) 6:48 
    PHP Allows the Following Explicit Type Casts 6:49 
    The settype () Function 8:18 
   Type Casting Coding Example 9:00 
    Explicit Type Casts 9:01 
   String Conversions 14:52 
    String Conversions 15:05 
    Common Conversions to String 15:55 
   Numeric Conversions 18:18 
    Numeric Conversions 18:19 
   Boolean Conversions 20:29 
    Boolean Conversions 20:30 
   Homework Challenge 21:38 
    Homework Challenge 21:39 
  Introduction to Functions 52:20
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   What are Functions? 0:51 
    Definition of Faction 0:52 
    PHP and Function Call 1:53 
   Function Calls 2:42 
    Function Calls 2:43 
    Function Arguments 3:17 
   Return Values 4:56 
    Return Values 4:57 
   Function Chaining 6:29 
    Function Chaining 6:30 
   PHP.net Function Reference 8:23 
    PHP.net & Function Prototypes 8:24 
    PHP.net Function Reference Example 9:29 
   Optional Function Arguments 12:28 
    Optional Function Arguments 12:29 
   String Functions 14:57 
    strtoupper() and strtolower() 14:58 
    implode (), str_replace(), explode(), strpos(), substr(), and strlen() 18:31 
   Array Functions 25:48 
    count() 25:49 
    in_array() and array_key_exists() 26:06 
    sort() and ksort() 26:37 
    Example: count() and in_array() 27:50 
    Example: array_key_exists() 29:53 
    Example: sort() and ksort() 31:20 
   Date & Time Functions 33:38 
    date() and time() 33:39 
    getdate() 34:49 
    mktime() 35:01 
    Date & Time Functions 35:12 
    Example: date() and time() 35:58 
    Example: getdate() 42:15 
    Example: mktime() 43:15 
   Homework Challenge #1 44:31 
    Homework Challenge #1 44:32 
   Homework Challenge #1 (Cont.) 45:28 
    Homework Challenge #1 (Cont.) 45:29 
   Homework Challenge #2 46:34 
    Homework Challenge #2 46:34 
   Homework Challenge #2 (Cont.) 48:06 
    Homework Challenge #2 (Cont.) 48:07 
   Homework Challenge #2 (Cont.) 49:17 
    Homework Challenge #2 (Cont.) 49:18 
   Homework Challenge #3 50:08 
    Homework Challenge #3 50:09 
  Constants 19:24
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Constants vs. Variables 0:55 
    Constants vs. Variables 0:56 
   Constant Identifiers 2:28 
    Constant Identifiers Definition and Examples 2:29 
   Declaring Constants 3:47 
    Two Ways of Declaring Constants 3:48 
    Syntaxes 4:10 
    Major Difference in the Two Forms 4:48 
   Using Constants Example 6:25 
    Using Constants Example 6:26 
   Coding Conventions 11:08 
    Constant Names 11:09 
    define () Function 11:42 
    Meaningful Names 12:00 
   $_SERVER Superglobal 12:23 
    $_SERVER 12:24 
    $_SERVER ['DOCUMENT_ROOT'] 13:15 
    $_SERVER Superglobal Example 13:52 
   Homework Challenge 17:40 
    Homework Challenge 17:41 
  Web Application Development 26:29
   Intro 0:00 
   Lesson Overview 0:13 
    Lesson Overview 0:14 
   Version 6.0 1:13 
    Version 6.0 & Version 5.1 Review 1:14 
   Version 6.0 Changelog 11:24 
    Version 6.0 Changelog 11:25 
   Version 6.1 Changelog 12:00 
    Version 6.1 Changelog 12:01 
   Version 6.1 Coding Example 12:42 
    Version 6.1 Coding Example 12:43 
   Version 6.2 Changelog 15:18 
    Version 6.2 Changelog 15:19 
   Version 6.2 Coding Example 18:19 
    Version 6.2 Coding Example 18:20 
   Homework Challenge 25:24 
    Homework Challenge 25:25 
  Conditional Control Structures 18:58
   Intro 0:00 
   Lesson Overview 0:26 
    Lesson Overview 0:27 
   Statement Groups 0:57 
    Statement Groups 0:58 
    Example 1:10 
   Conditional Control Structures 1:38 
    Conditional Control Structures 1:39 
    PHP Control Structures 1:56 
   if Statement 2:32 
    if Statement 2:33 
   if Statement (cont.) 3:49 
    if Statement Coding Example 3:50 
   else Statement 7:26 
    else Statement 7:27 
    if/else Statement Coding Example 8:50 
   isset() Construct 9:59 
    isset() Construct 10:00 
    isset() Construct Coding Example 12:00 
   Coding Conventions 15:13 
    Coding Conventions 15:14 
   Coding Conventions (Cont.) 16:39 
    Coding Conventions (Cont.) 16:40 
   Homework Challenge 17:25 
    Homework Challenge 17:26 
  Error Handling 19:08
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Error Handling in PHP 0:41 
    Error Handling in PHP 0:42 
    Coding Example 1:45 
   error_reporting() Function 7:02 
    error_reporting() Function 7:03 
    Coding Example 8:04 
   Additional Error Directives 9:02 
    display_errors 9:13 
    log_errors 9:37 
    error_log 9:50 
    track_errors 10:12 
    Coding Examples 10:29 
   Error Control Operator 13:38 
    Error Control Operator & Coding Example 13:39 
   Homework Challenge 16:19 
    Homework Challenge 16:20 
   Homework Challenge (cont.) 17:58 
    Homework Challenge (cont.) 17:59 
  Logical & Ternary Operators 23:22
   Intro 0:00 
   Lesson Overview 0:17 
    Lesson Overview 0:18 
   Logical Operators 0:49 
    Logical Operators Definition 0:50 
    NOT (!) 1:08 
    OR ( ||, or) 1:35 
    AND (&&, and) 2:08 
    XOR (xor) 2:30 
   Logical Operators (cont.) 2:54 
    The OR and AND Logical Operators 2:55 
    Precedence of Logical Operators 3:35 
   Logical Operators Coding Example 3:58 
    Logical Operators Coding Example 3:59 
   Short-Circuit Operators 9:54 
    Short-Circuit Operators 9:55 
    Coding Example 10:49 
   Ternary Operator 14:07 
    Ternary Operator 14:08 
    Syntax and Example 14:24 
   Coding Conventions 17:36 
    Coding Conventions 17:37 
   Homework Challenge 19:08 
    Homework Challenge 19:09 
   Homework Challenge (cont.) 20:26 
    Homework Challenge (cont.) 20:27 
  Web Application Development 19:27
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Version 6.2 Review 0:26 
    Version 6.2 Review 0:27 
   Version 7.0 Changelog 2:39 
    Version 7.0 Changelog 2:40 
   Version 7.0 Coding Example 4:35 
    Version 7.0 Coding Example 4:36 
   Version 7.1 Changelog 12:43 
    Version 7.1 Changelog 12:44 
   Version 7.1 Coding Example 13:52 
    Version 7.1 Coding Example 13:53 
   Homework Challenge 17:42 
    Homework Challenge 17:43 
  More Conditional Control Structure 20:49
   Intro 0:00 
   Lesson Overview 0:13 
    Lesson Overview 0:14 
   elseif Statement 0:45 
    elseif Statement 0:46 
    elseif Statement Coding Example 1:22 
   Multiple elseif Statements 2:16 
    Multiple elseif Statements 2:17 
    Multiple elseif Statements Coding Example 3:07 
   Adding an else Statement 5:44 
    Adding an else Statement Overview 5:45 
    Adding an else Statement Coding Example 6:50 
   switch() Statement 8:07 
    switch() Statement 8:08 
   switch() Statement (Cont.) 9:14 
    switch() Statement (Cont.) 9:15 
    switch() Statement Coding Example 11:09 
   default Case 14:20 
    default Case 14:21 
    default Case Coding Example 15:13 
   Coding Conventions 15:57 
    Coding Conventions 15:58 
   Coding Conventions (cont.) 17:10 
    Coding Conventions (cont.) 17:11 
   Homework Challenge 18:06 
    Homework Challenge 18:07 
   Homework Challenge (cont.) 19:18 
    Homework Challenge (cont.) 19:19 
  Nested Conditional Control Structures 24:49
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   Nested Control Structures 0:36 
    Nested Control Structures 0:37 
    Nested Control Structures Coding Example 2:08 
   Coding Conventions 6:34 
    Nested vs. Not Nested Control Structures 6:35 
   Debugging Control Structures 7:51 
    Debugging Control Structures 7:52 
    Incorrectly Specified Test Conditions and Forgetting a Break Statement 8:32 
    Incorrectly Placing an Opening or Closing Curly Brace 12:14 
   Debugging Tips 16:24 
    Tracing the Execution of Your Code 16:25 
    Adding Echo Statement 17:15 
   Homework Challenge 21:41 
    Homework Challenge 21:42 
   Homework Challenge (cont.) 23:08 
    Homework Challenge (cont.) 23:09 
  Web Application Development 28:20
   Intro 0:00 
   Lesson Overview 0:13 
    Lesson Overview 0:14 
   Version 7.1 Review 0:46 
    Version 7.1 Review 0:47 
   empty () Construct 1:38 
    empty () Construct 1:39 
    empty () Construct Coding Example 2:37 
   Version 8.0 5:32 
    Version 8.0 Overview 5:33 
   Version 8.0 Coding Example 7:08 
    Version 8.0 Coding Example 7:09 
   Version 8.1 16:13 
    Version 8.1 Overview 16:14 
   Version 8.1 Coding Example 19:48 
    Version 8.1 Coding Example 19:49 
   Homework Challenge 26:19 
    Homework Challenge 26:20 
  Sending Email Using PHP 43:50
   Intro 0:00 
   Lesson Overview 0:14 
    Lesson Overview 0:15 
   Built-in Mail Extension 1:28 
    Built-in Mail Extension 1:29 
   SMTP Overview 2:04 
    SMTP Overview 2:05 
   SMTP - Windows 3:08 
    SMTP - Windows 3:09 
   SMTP - Linux/UNIX 4:58 
    SMTP - Linux/UNIX 4:59 
   Mail Configuration Directives 6:35 
    Mail Configuration Directives 6:36 
    Coding Example 7:48 
   Mail Server Authentication 10:20 
    Mail Server Authentication 10:21 
   fake sendmail Program 12:27 
    fake sendmail for Windows 12:28 
    Main 'add-on' feature 13:03 
    Username & Password 13:25 
   SMTP - XAMPP for Windows 14:07 
    SMTP - XAMPP for Windows 14:08 
   Sendmail Example 16:19 
    Sendmail Example 16:20 
   mail() Function 18:39 
    mail() Function 18:40 
    additional_headers 19:45 
    'From' Header 20:12 
   mail() Function Coding Example 21:09 
    mail() Function Coding Example 21:40 
   Web Application Development 31:43 
    Version 9.0 Changelog 31:44 
   ContactUs.php 32:52 
    ContactUs.php 32:53 
    contactInfo 33:45 
   Version 9.0 Coding Example 34:31 
    Version 9.0 Coding Example 34:32 
   Homework Challenge 41:32 
    Homework Challenge 41:33 
  User-Defined Functions 56:00
   Intro 0:00 
   Lesson Overview 0:16 
    Lesson Overview 0:17 
   Defining Functions 1:29 
    Four Parts of Defining a Function 1:30 
    Functions Example 1 2:29 
   Function Parameters 5:29 
    Function Parameters 5:30 
    Functions Example 2 8:20 
   Return Statements 12:53 
    Return Statements 12:54 
    Functions Example 3 14:20 
   Where to Define Functions 20:34 
    Where to Define Functions 20:35 
   include_once Construct 22:10 
    include_once Construct 22:11 
    include_once Coding Example 23:55 
   Reasons to Use Functions 27:44 
    Take Advantage of Code Reuse 27:45 
    Improve Code Readability 29:56 
    Use Instead of 'content' Include Files 32:12 
   Web Application Development 34:42 
    Version 10.0 Changelog 34:43 
   Version 10.0 Coding Example 37:55 
    Version 10.0 Coding Example 37:56 
   Outputting HTML in Functions 47:04 
    Outputting HTML in Functions 47:05 
    Example 49:02 
   Coding Conventions 53:16 
    Coding Conventions 53:17 
   Homework Challenge 54:33 
    Homework Challenge 54:34 
  Variable Scope 31:37
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   What is Variable Scope? 0:57 
    Variable Scope 0:58 
    Global Scope 1:15 
    Local Function Scope 1:50 
   Variable Scope Coding Example 2:26 
    Variable Scope Coding Example 2:27 
   global Keyword 8:52 
    global Keyword Overview 8:53 
    global Keyword Example 9:25 
   Superglobals 12:34 
    Superglobals 12:35 
    Superglobals Example 14:53 
   Pitfalls of Global Variables 18:34 
    Pitfalls of Global Variables 18:35 
   When to Define Variables 22:09 
    When to Define Variables 22:10 
   Putting It All Together 22:56 
    Putting It All Together Example 22:57 
   Function Scope 28:56 
    Function Scope 28:57 
   Homework Challenge 29:41 
    Homework Challenge 29:42 
   Homework Challenge (cont.) 30:59 
    Homework Challenge (cont.) 31:00 
  Web Application Development 28:27
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Version 11.0 Changelog 0:56 
    Version 11.0 Changelog 0:57 
   processGetVar() 1:42 
    processGetVar() Overview 1:43 
    processGetVar() Example 2:25 
   emailComments() 6:35 
    emailComments() Overview 6:36 
    emailComments() Example 7:14 
   outputItemLink() 11:19 
    outputItemLink() Overview 11:20 
    outputItemLink() Example 11:45 
   calcCartTotal() 19:25 
    calcCartTotal() Overview 19:26 
    calcCartTotal() Example 21:14 
   Homework Challenge 25:56 
    Homework Challenge 25:57 
  Optional Parameters 19:35
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   Optional Parameters 0:26 
    Optional Parameters Definition 0:27 
    Default Values 0:53 
    Optional Parameters Coding Example 3:26 
   More on Optional Parameters 6:55 
    Multiple Optional Parameters 6:56 
    Coding Example 8:05 
   Homework Challenge 16:18 
    Homework Challenge 16:19 
  Web Application Development 23:07
   Intro 0:00 
   Lesson Overview 0:13 
    Lesson Overview 0:14 
   Version 12.0 Changelog 0:55 
    Version 12.0 Changelog 0:56 
   Update to outputLink() 1:44 
    Update to outputLink() 1:45 
    outputLink() Coding Example 2:40 
   outputImg() 13:57 
    outputImg() Overview 13:58 
    outputImg() Coding Example 15:35 
   Homework Challenge 22:05 
    Homework Challenge 22:06 
  Introduction to Conditional Loops 57:20
   Intro 0:00 
   Lesson Overview 0:08 
    Lesson Overview 0:09 
   while Loop 0:48 
    Definition 0:49 
    Syntax and Usage 1:12 
    Coding Example 3:33 
   Looping Over Arrays 13:16 
    Looping Over Arrays 13:17 
    Coding Example 13:53 
   Looping Over Arrays (cont.) 16:43 
    Internal Array Pointer 16:44 
   Array Traversal Functions 17:29 
    current () 17:30 
    next () and prev () 18:16 
    reset () and end () 19:25 
    key () 19:40 
   Indexed Arrays: Using current () and next () 20:40 
    Indexed Arrays: Using current () and next () 20:41 
   Associative Arrays: Using key (), current (), and next () 24:06 
    Associative Arrays: Using key (), current (), and next () 24:07 
   Array Traversal Functions (cont.) 29:41 
    list () Construct and Example 30:07 
    each () Construct and Example 34:40 
   Lopping Over Arrays Using list(), each() 42:13 
    Lopping Over Arrays Using list(), each() 42:14 
   Control Structure Scope 50:37 
    Definition and Example 50:38 
    Control Structure Scope Coding Example 51:59 
   Coding Conventions 54:20 
    Coding Conventions 54:21 
   Homework Challenge 54:58 
    Homework Challenge 54:49 
  More on Conditional Loops 35:50
   Intro 0:00 
   Lesson Overview 0:08 
    Lesson Overview 0:09 
   do-while Loop 0:42 
    do-while Loop 0:43 
    Simple do-while Loop Example 1:51 
    Another do-while Loop Example 4:09 
   continue Statement 10:46 
    continue Statement 10:47 
    For Example 11:07 
    continue Statement Coding Example 12:44 
   break Statement Re-Visited 18:10 
    break Statement Re-Visited 18:11 
    break Statement In while Loops Example 19:38 
   Infinite Loops 23:26 
    Infinite Loops 23:27 
    Coding Example 24:57 
   Common Loop Pitfalls 25:59 
    Counter Initialization Occurs in Loop 26:30 
    Counter Not Incremented in Loop 29:30 
    Unreachable Break Statement 30:50 
   Coding Conventions 33:48 
    Do-while Statements Coding Conventions 33:49 
   Homework Challenge 34:28 
    Homework Challenge 34:29 
  Web Application Development 22:07
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   Version 13.0 Changelog 0:48 
    Updating 'viewCart.php' and calcCartTotal() 0:49 
    Creating isValidCart() 9:22 
    Adding Three New Item to the Store & Links 15:56 
   Version 13.1 Changelog 17:20 
    Updating outputItemLink() to Remove Its Global Dependency on $itemCatalog 17:21 
   Homework Challenge 20:34 
    Homework Challenge 20:35 
  For & Foreach Loops 29:28
   Intro 0:00 
   Lesson Overview 0:11 
    Lesson Overview 0:12 
   for Loops 0:45 
    for Loops 0:46 
    Expression 1 1:22 
    Expression 2 1:47 
    Expression 3 2:01 
   Simple Example 2:27 
    Simple Example 2:28 
   Notes on for Loops 8:56 
    Notes on for Loops 8:57 
   Ending Loop Using Test Condition and Break Statement 10:06 
    Ending Loop Using Test Condition and Break Statement 10:07 
   foreach Loops 12:03 
    foreach Loops 12:04 
   Indexed Array Syntax 14:10 
    Syntax 14:11 
    Example 15:23 
   Associative Array Syntax 18:31 
    Syntax 18:32 
    Example 19:47 
   Coding Conventions 25:05 
    for Loops 25:06 
    foreach Loops 25:58 
   Homework Challenge 26:52 
    Homework Challenge 26:53 
  Web Application Development 25:58
   Intro 0:00 
   Lesson Overview 0:12 
    Lesson Overview 0:13 
   Version 14.0 Changelog 1:19 
    Version 14.0 Changelog 1:20 
   Version 14.0 Coding Example 1:57 
    Version 14.0 Coding Example 1:59 
   Version 14.1 Changelog 5:39 
    Version 14.1 Changelog 5:40 
   Version 14.1 Coding Example 7:06 
    Version 14.1 Coding Example 7:07 
   Version 14.2 Changelog 15:37 
    Version 14.2 Changelog 15:38 
   Version 14.2 Coding Example 16:25 
    Version 14.2 Coding Example 16:26 
   Homework Challenge 23:35 
    Homework Challenge 23:36 
  Conditional Loop Wrap-Up 23:12
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Nested Conditional Loops 0:39 
    Nested Conditional Loops 0:40 
    Coding Example 1:10 
   continue & break Re-Visited 5:17 
    Continue Statements and Coding Example 5:30 
    Break Statements and Coding Example 11:34 
   Loop Debugging Tips 15:16 
    Add Short Debug Statement At the Very Beginning 15:17 
    Output a Counter Variable 18:10 
    Add Debug Statement At the Very End 19:20 
   Homework Challenge 20:20 
    Homework Challenge 20:21 
   Homework Challenge (cont.) 22:00 
    Homework Challenge (cont.) 22:01 
  Variable-Length Parameter Lists 22:16
   Intro 0:00 
   Lesson Overview 0:09 
    Lesson Overview 0:10 
   Variable-Length Parameter Lists 0:34 
    Variable-Length Parameter Lists 0:35 
    Coding Example 1:51 
   Variable-Length Parameter Lists (cont.) 5:21 
    When a Parameter List is Defined For the Functions 5:22 
    Coding Example 6:32 
   Variable Type Functions 9:54 
    is_int (), is_float (), is_string (), and is_bool() 9:55 
    is_ array () 10:50 
    is_null () 11:01 
    Variable Type Functions Coding Example 1 11:27 
    is_numeric() and Example 15:57 
    Variable Type Functions Coding Example 2 17:12 
   Homework Challenge 19:35 
    Homework Challenge 19:36 
   Homework Challenge (cont.) 20:52 
    Homework Challenge (cont.) 20:53 
  Web Application Development 38:36
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   Version 15.0 Changelog 0:33 
    outputLink (), outputImg (), is_array () and is_string () 0:34 
   Version 15.0 Coding Example 1:31 
    Version 15.0 Coding Example 1:32 
   Version 15.1 Changelog 7:55 
    Removing Redundant Code and Adding New Function Called outputHtmlTag () 7:56 
   Version 15.1 Coding Example 8:37 
    Version 15.1 Coding Example 8:38 
   Version 16.0 Changelog 14:55 
    Creating emailOrder() Using New Constants ORDER_EMAIL_FROM and ORDER_EMAIL_SUBJECT 14:56 
   Version 16.0 Coding Example 16:30 
    Version 16.0 Coding Example 16:31 
   Version 16.1 Changelog 32:21 
    Creating formatAsDollars () 32:22 
   Version 16.1 Coding Example 32:57 
    Version 16.1 Coding Example 32:58 
   Homework Challenge 36:27 
    Homework Challenge 36:28 
  Miscellaneous Topics 31:49
   Intro 0:00 
   Lesson Overview 0:10 
    Lesson Overview 0:11 
   register_globals Directive 0:58 
    register_globals 0:59 
    Coding Example 2:04 
   $_GET vs. $HTTP_GET_VARS 4:07 
    $_GET vs. $HTTP_GET_VARS 4:08 
    register_long_arrays Directive Coding Example 5:44 
   Magic Constants 7:30 
    Magic Constants 7:31 
    __LINE__, __FILE__, __FIR__, and __FUNCTION__ 8:16 
    Coding Example 9:06 
   exist() & die() 13:19 
    exist() & die() 13:20 
    Coding Example 14:08 
   Execution Operator 16:23 
    Execution Operator 16:24 
    Coding Example 17:27 
   Array Operators 18:23 
    Equality (==) and Inequality (!=, <>) 18:43 
    Identity (===) and Non-Identity (!==) 19:13 
    Union (+) Operator 19:41 
    Array Operators Coding Example 20:07 
   Variable Variables 24:13 
    Variable Variables 24:14 
    Coding Example 26:07 
   Variable Functions 28:02 
    Variable Functions 28:03 
    Coding Example 29:13 

Hello, and welcome to the first lesson in Educator.com's Introduction to PHP course.0000

In today's lesson, we will be providing an overview of the material0005

that we are going to cover in this course, as well as providing an introduction into what PHP is.0008

What actually is PHP?0015

Well, the name itself is a recursive acronym that stands for PHP Hypertext Preprocessor.0016

The name is not so important as actually what PHP is.0023

What PHP is, is a general-purpose scripting language, which is a particular kind of programming language.0025

Its most common use, and the use we are going to be using it for in this class, 0032

is as a server-side scripting language that allows you to create dynamic web pages and interactive web applications.0036

It allows programmers to create web pages that have dynamic page content, such as dynamically-generated search results.0044

It allows programmers to create web pages that can process user input, such as input from HTML forms.0053

It allows programmers to have a code that performs services, like accessing databases and even processing credit card transactions.0060

There are actually a lot of server-side scripting languages out there in the world; why learn PHP?0070

In this slide, we are going to go over some of the reasons.0077

The first one is that it's the most popular server-side scripting language in use today, by far.0080

Additionally, it is free and open-source, and it works on all major operating systems and with the majority of modern web servers.0086

Additionally, you can quickly and easily get started with it, but it also provides advanced features.0095

So, it's a powerful and robust language.0101

One of its key features is that it can easily interface with most modern databases, like MySQL.0104

It does so using built-in extensions that come directly with the PHP core.0110

And finally, it is also the language behind some of the Web's most popular Web frameworks and contact management systems,0116

such as CakePHP, CodeIgniter, and Zend Framework, which are three different common frameworks used,0123

and then, some content management/web framework systems, such as Drupal, Joomla!, and WordPress.0130

Additionally, PHP, because it is so widely used, has an extremely large user base and is extremely well-documented.0137

In this course, we are going to be teaching the concepts of PHP by building up a fully-functional sample Web application.0147

The Web application we are going to be creating is a mock Web store called the Educator Store.0156

It is going to do a couple of things.0163

It is going to implement a simple shopping cart, and it is also going to have a form0164

where customers can email their comments to the store administrator directly.0167

If you go ahead and continue on with the PHP course sequence here at Educator.com and take the Advanced PHP course,0173

the development of this Web application will continue in the advanced course, as well.0180

When new concepts are presented, like session management, MySQL database integration, and object-oriented design,0185

you will be able to see how they get integrated into this Web application that we started off in the introductory lesson.0193

Let's actually take a quick look at what the final Web application is going to look like.0199

If we browse to the final version of our Web app, and we go to the homepage (it's called store.php),0210

you can see, it's a simple store interface.0216

Basically, it has a couple of different departments: Apparel, Electronics, and Sporting Goods, each with a couple of different items in it.0219

Right now, it's just the basic store; it just has a few items.0226

If you click on any of the department names (for example, in this left-hand navigation bar--bring this up and make it a little bigger),0229

you can see the items that are contained in that department--in this case, an LCD television and a DVD player.0238

It shows the price of the items.0245

And actually, if you click on any of the items, it takes you to an information page for that particular item.0247

It shows the item's number, its price, a larger image of the item, and then a comment or description about what the item is.0253

The Web store also provides a simple Shopping Cart form0262

that allows you to select which items in the store you would like to purchase, and then go ahead and check out.0267

If we go ahead, for example, and select one of each of these items that are currently in the store,0272

and go ahead and check out, it is going to calculate our Shopping Cart total.0282

In this case, it is going to be using a sales tax calculation as well.0287

And then, it is going to ask you to enter your shipping information.0291

I'm just going to go ahead and enter some sample information here.0295

And then, what you can do is: it allows the customer to click on the Complete Order button.0309

What it is going to do is output a message saying that your order was completed on a certain date at a certain time.0318

It is going to tell you the total of the order,0323

and it is basically going to echo to you the address that you provided for shipping the products you chose in the Shopping Cart.0325

The other thing it is going to be doing behind the scenes is:0334

it is actually going to be integrating email functionality, so that when a customer submits an order on the website,0336

an email is sent to the store administrator containing the information about the Web order.0343

For example, if we load our email client (in this case, Thunderbird), and we look at the email that was generated from this Shopping Cart,0349

we can see, it is an email that was sent that says, "Your order from Educator Store was made on this date and time."0357

And then, it provides a description of the different items that were purchased, their prices and which quantities,0363

the total of the order, and then the shipping information for the customer.0368

The other option that the store provides is a Contact Us form, 0374

which allows a user to email comments about the store to the store administrator,0378

which is a common functionality on many websites out there.0383

I'm just going to go ahead and demonstrate this quickly--provide some test comments to the site.0387

When the user goes ahead and clicks on the Contact Us button, it's going to send out an email to the store administrator.0399

In this case, it outputs a message that says "Thank you for your comments."0406

And actually, the store administrator can go and look in their store admin account (in this case, we're using Thunderbird),0409

and we can see the comments that were submitted by the user.0420

It says, "Matthew Machaj has had some comments for the store," and then lists the comments that I had submitted.0423

This Educator store is interesting, because it demonstrates many of the features and capabilities that are what make PHP so great.0434

One of the main things it does is: it shows the use of dynamic content generation.0443

You can see that when we go back to our Shopping Cart.0447

And if we select one item from the store, and we go to Checkout, you can see, it calculates the total and then outputs it.0456

This total is not hard-coded into this HTML page.0463

It is something that is dynamically calculated and dynamically output each time a user submits a Shopping Cart.0467

Additionally, the store demonstrates how using PHP can ease website maintenance.0476

The way it does that is sort of allowing a template system to be developed.0481

For example, if we look at any of the items in the store, the URL of the items--0486

the page that displays the items' information is actually all the same URL; it is called item.php.0493

But what PHP allows us to do is to pass information (in this case, an item ID) to the web page,0499

so that it can dynamically load information about a particular item and load it up for the user.0506

What that allows us to do is have one PHP page to maintain that outputs information about a particular item,0512

even though we may have thousands of items in the store.0518

That greatly increases the maintainability of the application, because instead of having to have a separate page for maybe 1,000 items in the store,0521

we have one PHP page that is just able to load information from sort of a database.0528

We are not going to use the actual database here, but sort of a catalog that is on the back and contains information about all of the different items in the store.0533

Additionally, the store shows how, with PHP, you can use form-input processing.0543

We saw that in two places.0547

One was where the user entered their shipping information; that was an HTML form.0548

And then also, when the user submitted comments in the Contact Us form...0553

It also shows how PHP provides a lot of built-in-advance functionality.0557

For example, in this application, we use email functionality in two spots--0562

both in emailing the contents of the order to the store administrator, and also emailing a user's comments from the Contact Us form.0566

What are you actually going to learn about PHP in this course?0578

First, you are going to learn about some Web fundamentals--the basics of how websites and PHP work together.0582

And then, we are going to go through and teach you how to set up a local PHP development environment,0589

which will allow you to practice the code examples in the course, work on the homework challenges, and begin to develop your own PHP code.0594

This is a key issue to go over, because that is one of the common roadblocks for a new PHP developer:0603

actually getting their development environment set up.0608

We are going to help to walk you through that process.0611

Additionally, we are going to cover all of the PHP programming basics: things like syntax, datatypes, and variables.0613

There are a bunch of other things you can see here, such as constants, operators, control structures, and even user-defined functions.0619

We are going to learn how to process form data in PHP, which is going to include a review of how to use HTML forms.0625

One of the most interesting things is: we are going to learn how to use include files and user-defined functions0633

to develop scalable and flexible Web applications.0638

The way we are going to learn how to do that is by being able to reuse code in multiple spots.0641

We are also going to cover solid programming practices and methodologies, so that you become a good programmer.0646

Who is this course designed for?0658

Basically, it is designed for Web developers seeking to build their Web development skill set,0660

so that they can learn to add dynamic content and advanced functionality to their websites.0666

Students, as a basis, should have a solid understanding of HTML, and to a lesser extent, have a menial understanding of Cascading Style Sheets.0673

Additionally, one of the key things to note is that it is assumed that students have little or no prior programming experience.0684

So, this is not only an introduction to PHP, but in a way, it's an introduction to programming.0691

Because of this, the course actually kind of breaks down into three different categories of material.0695

The first one is just going to be programming basics.0702

This is programming concepts (such as what a variable is, what an if statement is...) that apply to all programming languages.0704

And then, we are going to learn how to apply that specifically using PHP.0710

We are also going to be covering Web fundamentals (such as, again, how the Web works).0715

We're going to be learning about the http protocol, for example, and how that relates in a PHP-specific way.0720

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you at the next lesson.0728

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be continuing work on our web application for the mock store that we have been developing.0004

We are going to be integrating the material we learned in our last lesson on arrays.0009

In today's lecture, we are going to have four different versions of the web application store that we are going to go through.0016

The first one, version 3.0, is going to upgrade from our last one, which was 2.1.0023

What that is going to do is: we are going to create a new type of include file that is just a PHP file.0029

It is going to centralize all of our product information, like the item information, 0036

such as the name of the product, its image, the description, and so forth.0042

We will see, that becomes quite useful.0047

After we do that...when we centralize it, we are going to be creating an array in a PHP file, and so we are going to, in version 3.1,0049

improve the readability of our application by making an array an associative array.0059

Then, we are going to, in 3.2, make use of a multidimensional array; and finally, in version 3.3, 0065

we are going to make use of include files again, as we will find out that there is another opportunity for us to use code reuse.0072

Let's take a look at application version 3.0.0080

Actually, this is version 2.1, which is the last version we went over; and as you can see, this is the store.php page.0086

It is the same as it was in the last lesson.0096

What you can see is that we have things like "100% Cotton T-shirt" and "42" LCD Television" hard-coded as links into our homepage.0098

The homepage is going to look like this, if you remember.0110

For example, if we click on 100% Cotton T-shirt, it goes to the cotton T-shirt page.0121

Well, this 100% Cotton T-shirt phrase is hard-coded into the page, so if we want to change the name of the T-shirt, we have to change it here.0125

And then, because we used the name here on the actual product page, we have to change it here, as well.0134

We are going to make it easier to do that by creating a...we're going to call it a configuration file...that is going to contain all of the item's information.0138

Instead of having hard-coded values like this (for example, this is the store page--we have hard-coded all the names of the different products),0151

on the item page, like item-101 (oops, I want that closed)...0160

For example, item-1001.php from the last version--all of the information about the T-shirt is hard-coded: 0168

the item number, the price, the name of the image, the description.0178

What we are going to do now is: we are going to create new versions of these pages.0183

To start off with, let's look at the store.php, which is the homepage.0189

If you'll notice, there is a new line at the beginning here--there is a new include statement that says include catalog.php.0194

What catalog.php is: it's a PHP file that contains information about all of the items in our store, sort of like a central repository.0201

If we look at catalog.php, we can see that it contains three arrays, and we have created an array for each item in our store.0213

Right now, we only have three items, and we have called each array item, followed by the item number (so we have item-1001).0223

And then, in the array, in the same order for each of the different arrays (and these are numerically indexed arrays),0232

the first value is the item number; the second value is going to be the name of that particular item.0240

So, item number 1001 has the name 100% Cotton T-shirt.0247

It has the price 14.99; its image is 1001.jpg; and then, the description that we are going to use is "This 100% cotton T-shirt is built for comfort."0252

We have a similar thing that happens for both item 2001 and item 2003.0265

So, what that is going to allow us to do: because we have included that at the beginning of our store.php page, 0272

now all of those variables that were included in that file are available in the rest of our PHP page.0279

So, when we go down here and we want to list the name of item 1001, 0286

we can use a PHP echo statement that makes reference to the item-1001 array defined in catalog.0294

We are going to get the second item out of that array, which happens to be the name.0302

So, if we go back here, we can look, and we can see the item-1001; the 1 index refers to 100% Cotton T-shirt.0305

And what that is going to do is allow us to access that information.0315

This is in contrast to in our last one, where it was hard-coded; we just had 100% Cotton T-shirt written in there.0322

Now, we have it stored in one file, and so, anytime we want to access the name of that particular item, we can just access that array.0331

Similarly, on the previous item-1001.php page, all of the information about that item was hard-coded--the name, the item number, the price, and so forth.0338

Well, in our new version, we are going to add that include file again to the top of the page, 0353

which is going to make all of those arrays that we defined in catalog.php available in this script.0358

What we are going to do is: we are going to echo the different values contained in those arrays.0367

So, for example, the item name is the second item we are going to reference.0374

Because this is the page for item-1001, we are going to reference the item-1001 array, the second element, which is the name, and so forth.0377

And so, down here, we are going to access the item ID; we are going to output the price.0388

Within this image tag, we are going to output the name of the image file, and that is useful for...0395

if we want to change an image file, maybe from a GIF to a JPEG, we can just update it in the catalog.php file.0402

And any page that uses that product's image, we can update using this array.0408

And then also, down here, we output the product's description.0417

This was the old version, and then this was the new version; and we actually can even improve on this further.0429

But before we talk about that, let's go ahead and look at...this is what the old website looked like, 0438

and the new website is going to look exactly the same--version 3.0--it is just going to be making use of these arrays.0442

Just to verify that, we are going to go up here and take a look at it; and you can see, it's the same website.0450

I think the name of the store changed, because we played around with that in the last lesson.0457

And, if we click on each of the different product pages, we can see that all the information for that product is output.0462

If we read the page source, we can see that all of that information about the item that was output by accessing those arrays0470

in catalog.php has been output to the file.0483

We can improve on this even a little more, and that is going to take us to version 3.1, and we are going to make use of associative arrays.0488

Let's go back here and go to version 3.1.0499

OK, now what we have done is: for version 3.0, we had numerically indexed arrays for each item.0517

And what we have done in version 3.1 is: we have updated catalog.php and turned them into associative arrays.0527

And so, what we have done (bring that up) is: instead of having to access the different values in this array using numeric indexes,0535

which don't have much semantic meaning to them, we associate each value with a particular key that has meaning.0548

So, we are associating the item ID with a key named itemID; we are associating the name of the item with the name key; and so forth.0556

We have price, imageFile, and description--the other keys we are going to use in each of these different arrays.0565

And so, what that is going to do is: it makes our code a little bit easier to read, because when we reference, for example, the name of item 2001,0570

we are going to, using square bracket notation, see item-2001 array name with the square bracket with the string name on the inside.0578

So, it is going to kind of intuitively tell us, "OK, we are getting the name of that," as opposed to before, 0587

when it was just the number 1, which doesn't have as much meaning.0591

If we go and look at the new...for example, store.php page, we still have the include up at the top--the catalog.0595

But now, whereas before we had...when we wanted to, for example, output the name of item 1001, 0607

we used this array in catalog.php, which is numerically indexed.0618

In the new version of it, it becomes item-1001 name, and so it's a little more intuitive, and we can instantly grasp some meaning0623

as to what the value we are going out and outputting is used for.0631

Similarly, on the product pages, we still have the include for catalog; it's going to include for the new associative array catalog.0637

Now, when we go ahead and output information about it, such as the name, its ID, its price, and image file,0646

we are going to access the arrays in catalog.php, using the string keys.0652

What that is going to do, again, is: it adds a little more semantic meaning to our code.0661

So, we can look down here and know, when we are editing this code, "OK, here is some HTML that is outputting the phrase price and a dollar sign."0666

And then, I am going to echo from PHP an array called item-1001, which intuitively tells you, "OK, this is probably item-1001 in the catalog."0673

And then, we are going to output a value that is associated with the key price.0683

Likely, it is going to be a price; and so, it gives meaning to our script and makes it easier to read.0688

This website is going to look exactly the same as the last one did.0695

We haven't changed any of the code--it's just that we have used an associative array to sort of improve things.0698

We are actually going to take it one step further now, and for 3.2, we are going to make use of multidimensional arrays.0703

That is going to clean things up a little bit.0710

The way that is going to work is (let's go back here and close down some of these older versions...OK, and go to version 3.2):0713

now, let's take a look at catalog.php again...0745

This time, we only have one array to find in here; it is called items, and it is a multidimensional array.0748

Let's clean these lines up; I don't know why they changed.0758

And so, basically, it has the same content of the previous catalog.php, except instead of having three different arrays0761

that we needed to reference using the particular variable identifier we assigned to the array,0771

we are going to combine all three of those arrays into one array called items.0781

It is going to be a numerically indexed array, and it is going to contain all the information for each item--so it's going to contain...0786

Actually, this formatting is off, so it makes it a little harder to read; I'll just fix this really quickly.0801

In the items array, it is going to have three elements in it, and the key for each element is going to be the item ID.0822

So, the key 1001 is going to refer to information about item 1001.0831

To each item ID, we are going to assign a value, which is an array, 0838

that contains the name, price, image file, and description information related to that item.0843

If we go back and we look at store.php, and we include catalog.php, now the way we access things is using the multidimensional square bracket syntax.0851

We reference...for example, here we want to output the name of item 1001; so, this right here tells us 0866

to pull up item-1001 from the items array, and then get the name value associated with item-1001.0872

This is opposed to the previous version, where we actually had an array created for each different item.0883

Item 1001 needed its own array created in catalog.php; item 2001 needed its own array created in catalog.php.0893

Now, we simply use the same array for all of the different item numbers, and we simply add an additional square bracket in there0903

to refer to the item number in the multidimensional array.0913

If we look at the product pages, we can see the same thing is done.0917

We have the catalog.php inclusion, and what we have done is accessed the 1001 item number.0923

We are going to output the name associated with product ID 1001; we are going to output the price; and so forth.0934

We are accessing it using square bracket notation for multidimensional arrays.0944

And you can see up here, too, that the title which essentially gets passed to the header file to be output as the HTML title--0950

we are going to set it equal to the name of the particular item.0962

So before, we have done that in previous examples--we dynamically set the name of each page.0970

Now, we are doing it using the array; and actually, in the other two versions that we talked about (3.0 and 3.1),0976

we did the same thing, using the different syntax.0981

For example, in the last one, because we still had the individual item arrays, this is how we set the title.0985

One interesting thing we can do here is: you look at, for example, item-1001.php; 0994

we can see that we have this number 1001 output several times throughout the script.1000

And so, any time we see code that is redundant like that, we want to take advantage of the opportunity to reuse it,1006

because what that is going to do is eliminate the number of errors, because every time we need to reference item 1001,1012

we need to type this string; and each additional time we do that, that gives us one more chance for an error.1018

So actually, what we can do is create, at the top of the page, a new variable called itemID; and we are going to set it to 1001.1024

What we can do now is: everywhere where we have 1001, we can go through and replace it with the variable itemID.1042

I'll use the Search and Replace feature to do that.1056

And, as you can see, what we have done is replaced all of these 1001's that were referenced down here with itemID up here.1077

So now, any time you want to update the item number, we only have to do in one spot, not in (in this case) 1, 2, 3, 4, 5 different places.1083

Additionally, because we are going to be passing the name of the item on to the header include file, we're going to get rid of this 1001, too.1091

And so, we include itemID here; and what is key to notice is that, because we use itemID in the creation of the variable title,1103

we have to have itemID defined ahead of time.1113

If we had defined it below it, then we would get an undefined variable error, and the title would not be able to be properly output.1115

Let's set that back to normal.1126

And so, we actually could do this for every single page in version 3.2.1132

For example, for item 2001, we can create variable itemID, and then we are going to go through and replace all of the 2001's with itemID.1143

And we have the same thing as on the 1001 page.1165

We are going to go ahead and do that for 3001; and there is an important reason 1172

why I am walking through and doing this individually, and you will see it in one second.1176

Actually, I need to replace the original one...oops, I had an extra apostrophe in there.1200

OK, so now, for item 3001 page, we define the number up here; itemID is 3001, and then we reference it down here 1212

in the body of HTML that outputs information about that item.1220

Now, if you actually look (after we have made this adjustment) at item-2001.php, we can see that this whole file 1228

is exactly the same, except for this number up here.1236

And if we look at item-1001, the content is the same except for the 1001 up here.1240

So again, we have another opportunity for code reuse; and so, that is what we are going to do as we move on to 1245

the next version of the website, and the last version we are going to go over today, which is version 3.3.1254

What we are going to do is place all of this common text into an include file, and it is going to simplify our website again,1258

because it is going to move content that might be in, in this case, three different pages.1265

And if we want to make a change to it, instead of having to change three pages individually, 1270

we simply go and update the include file that we are going to create.1274

Let me close some of these down; and let's go pull up the file for 3.3.1279

In this version, we have the same exact associative array containing all of our items in catalog.php, so that has not changed.1317

Let me close these.1326

store.php is exactly the same as before, except here--we didn't do it on the last one, but--we could actually update this...1328

Actually, we couldn't do the same thing with the itemID, because it references different items in this.1340

So, store.php is going to stay exactly the same; however, item-1001.php, which used to look like this, 1346

which has all of this common code here, is now going to be changed to look like this.1357

It has a lot less information in it; and what it is going to do is: it's going to take out the HTML 1363

that outputs information about the particular item, and it's going to put it in an include file, and we've created a new include file called itemListing.phtml.1369

It is called .phtml because it contains both HTML and PHP code.1378

We have taken that and removed it there; and then now, on each of our item pages, 1383

whereas before we would have this code after the include for the header file, we simply add another include statement for listing .phtml.1388

Now, the itemListing.phtml is going to reference this itemID defined in the beginning of the file.1400

And as we can see here, we use this itemID as we had described it in the last lesson.1409

So, itemID, again, has to be defined before this file is called, so that the variable is available.1414

So now, if we look at the three pages we have for our three products, item-1001, 2001, and 3001--1423

they are exactly the same, except for the item number listed.1430

So again, what that has done is consolidated our code into one spot, so if we want to change something, for example--1436

like...let's say that we want to place the image instead...well, right now, let's take a look at the web app.1443

In version 3.2, which is our last version, for the Baseball Bat, 1001, this is what our product page looks like.1455

We have the baseball bat above the description; and that is the same for the T-shirt and the LCD television; the picture is above the description.1463

Let's say that now we decide we want to actually put the description above the image.1475

What we can do is...now, we go back to our itemListing.phtml page, and what we can do is take this image tag and move it below the description.1480

What that is going to do is: it is going to put the image below the description in every single one of our product pages.1497

So basically, any time we want to change the layout of how the product pages look, we only have to do it in one file, in this one include file.1502

If we save this and we browse to version 3.3, and we go to Cotton Shirt, we can see that the shirt now is below the description.1510

It has done that for every single one of our products.1523

And likewise, if we decide we want to take it back--simply undo the change--make the change in one spot, 1529

and it is going to replicate to all of our different pages.1537

And we go back, and things are back the way that they were.1540

So, this is another example of code reuse, using an include file1549

And we are going to continue to use that theme of extracting out redundant code, and putting it in one place,1553

so that you edit it once, and then it has effects throughout different parts of the website--multiple pages at once.1559

It increases the ease of management and your efficiency, because you only have to manage and update one file,1565

instead of maybe...let's say our store had 1,000 products in it; you might have to update 1,000 HTML pages or 1,000 PHP pages.1572

Now we just have to update one, and it reduces the risk of errors, 1580

because instead of having a possible 1,000 chances to make an error, you only have one spot to make that error.1584

That ends our discussion for going over the web application--the changes that we are going to make.1592

I just want to also give you a homework challenge for this lesson.1598

Basically, what I would like you to do is: you can download the web application files and the new versions from the Educator.com website.1603

What you should do is go through and look through the web application files, 1614

making sure that you understand what changes were made from one version to the next.1617

For one, we went from a numeric array to an associative array, and we went from an associative array to a multidimensional array.1621

Then we changed things to make an include file.1628

Equally important as noticing the changes, I want you to try and understand why the changes were made1632

and how they serve to improve the site--how they improve things, 1637

as far as the efficiency and reduction in opportunities for errors, and also just in code readability.1641

And hopefully, that will give you a better idea of the purposes behind why we are making these changes to the web application.1650

That ends today's lesson; thank you for watching.1656

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be talking about how to provide input to your PHP script,0004

and specifically how input is provided using the GET HTTP method.0009

In today's lesson, we are going to talk about a couple of different methods that are available for providing input to a script.0017

We are going to talk, in particular, about the GET method, which is what we are going to be using throughout this course.0024

We are going to do a slight review of HTML forms, and then go over something known as URL encoding.0030

How do you provide input to a PHP script? Well, there are three basic ways that you can do that.0041

There are two HTTP methods known as the GET method and the POST method, 0046

and if you have worked with HTML forms before, you may be familiar with that.0051

Also, you can use what are known as cookies to provide information, as well.0054

In this course, we are only going to be dealing with the GET method; and the reason for that is that the POST and cookie method0060

are somewhat more complicated and advanced topics, so we are going to save them for the advanced course.0065

In addition, by using the GET method, it makes debugging our scripts easier.0071

In a sense, we are just learning PHP, and we are going to be making mistakes along the way; using the GET method is going to help us with that.0075

Now, the way that these methods work, whether it's GET, POST, or cookies--they provide information to a script by name/value pairs.0082

For example, you might have the name username, which is just a property, let's say, called username; and you are going to set it the value JSmith.0091

Or, the user using your HTML web page is going to set that value.0102

This is a name/value pair, and what is going to be done is: it is going to be sent to the web server when the user submits the web page.0108

Now, let's talk a little bit more about the GET method, the HTTP method GET,0118

and how it works to provide input to a PHP script--or, in fact, any other script.0124

What it does is: it appends the name/value pairs that we had just talked about, or any number of name/value pairs,0129

to the destination script's URL; and it does so in the manner shown down here.0136

So, for example, we have a script named process.php, and using GET, we want to pass it a name/value pair.0143

In this case, we have name1 as the name and value1 as the value; they are just sample values for those.0152

The way you append them is with a question mark.0159

And so, any time the GET method provides input to a script, it does so appending stuff to the end of the URL.0164

When you append the name/value pairs to a URL, that is known as a query string.0173

So, everything after the question mark in this particular link is known as a query string, and it's composed of name/value pairs.0180

Now, one thing to note is that the GET method can actually be used to input data to a script using HTML forms, or it can be done manually.0188

So, when you have an HTML form (which we are going to get to in a little bit), you can set it to use the GET method, 0199

and the HTML form automatically appends the name/value pairs you submit, that are created by your form, to the URL for you.0205

You alternatively can do it manually, as well, which we are going to look at a little bit towards the end of the lesson.0213

Let's take a look at a script here I've created called simpleForm.html.0220

Basically, what it is: it just has a simple text field and a Submit button.0228

Again, we are going to get into forms in a little bit; but it uses the GET method to submit things.0231

And so, if I type my name in--Matthew--and click Submit, you can see, up in the address bar of the browser, 0237

that it has appended to the URL simpleForm.html a question mark, followed by text1=Matthew, 0246

text1 being the name of the name/value pair, Matthew being the value that I supplied to the form.0254

You can also see that the question mark has been appended to simpleForm.html, which means, 0261

when I submitted this form, I submitted it to the same page.0267

In this case, it submitted it to an HTML page, simpleForm.html; now, because simpleForm.html is just a raw HTML page,0271

it doesn't have the capabilities to process any input passed in the URL by a query string.0280

So, in this case, it actually does nothing; and what we are going to be doing in this course is using PHP scripts to receive the input.0287

And so, instead of having simpleForm.html followed by a query string, it might be simpleForm.php followed by a query string.0295

What that is going to do is load up a PHP script that is going to know how to extract the name/value pairs from this query string.0302

We are going to begin talking about that in the next lesson.0311

One thing I wanted to note: if you can see here, we had Firebug set up at the bottom of Firefox.0314

And the way you access that, again, is by clicking on the little bug icon in the bottom right-hand corner of the window.0320

There are a couple of different panels here; and today, we are going to be working with the Net panel.0327

And what you can see is: the Net panel provides information, for example, 0332

about the HTTP that is going on behind the scenes when you request the web page.0336

So, when you request a web page...in this particular case, we requested the web page simpleForm.html, using the GET method.0341

We send that HTTP request to the server; in response, the HTTP server sends a response back,0349

which in this case, because it was the same page--it just outputs the same page.0358

Now, what you can do is: if you select the Net panel and select All from the next menu bar, you can click on the plus sign,0364

and what you can see is: there are a couple of different tabs; and the one we are going to click on is Headers.0377

What this shows is information about the request that was sent from your browser to the web server when you submitted the form,0383

and then the response that was sent back.0391

If we go down to the request header section, and if you click, there is a View Source link that you can click on.0393

It is going to show the raw HTTP header, and that is actually what was sent by HTTP to the server.0401

You don't need to be concerned with the details of what is included in this header; there is a lot of information there.0409

We are basically just going to be concerned with the first line, and the format of the first line of a request header is a method name 0415

(in this case, it's GET, because we used the GET method), followed by the file or resource we were requesting, which is simpleForm.html.0423

And then, it also lists the HTTP version number that it is using.0433

However, as you can see, when we submitted the form, the URL is not just simpleForm.html; 0437

it actually has a question mark with text1=Matthew appended to it.0442

And so, that is an example of a query string; and as we can see, using Firebug, this is a way to see what was submitted to a script.0447

And you will find, down the road, it will be a useful debugging tool.0460

Now, it provides the same information that was shown up here in the window, but it also provides a little more information.0463

And it also has a Params tab that will actually show you all of the name/value pairs that you submitted by a GET.0469

And, for example, you can see that we have that text1 is a name we submitted, and the value we set it to was Matthew.0481

And so, this is an example of using Firebug.0489

So now, let's talk a little bit about HTML forms; and this may be a review for some of you.0498

Basically, HTML forms are one way of submitting input to a script, and they can be done by the GET method 0503

or the POST method, which some of you may be familiar with.0510

We are only going to be talking about the GET method in this course.0513

Basically, HTML forms are composed of what are known as input controls, and each input control 0517

(such as a text box, or a dropdown menu, or a check box) has a name associated with it.0523

When the form that the input control is a part of is submitted to the web server, the current value associated with each input control0529

is associated with the name of the input control and sent as a name/value pair to the web server.0539

And, as mentioned, it does it by using the GET method as a query string, and it appends it to the end of the URL.0545

The way it does that is that each input control, as we will see, is an HTML tag that has a name attribute and a value attribute.0553

The value attribute is not always set, but the name value is always set; 0565

and when you submit the form, that is going to be the name that is going to be submitted in the query string.0571

So, for example, you may have a text field that asks for a user's username, 0577

and so the name you might assign to it--the name attribute--would be username.0583

So, in your query string, it will say username= and then the value will be whatever value the user had entered into that text field onto the form.0588

So again, basically, what happens is: when a form is submitted, 0597

the name of each input control, along with its current value, are sent over to the web server.0600

How do we declare a form in HTML? And again, some of you may have experience with this.0609

The way we do it is using the form tag; and the form tag can contain input tags, select tags, option tags, and text area tags.0614

What those are, are input elements that will supply name/value pairs to the server when the form is submitted.0627

Now, the form tag itself has two important attributes: one called method and one called action.0635

The method attribute can be set either to the value GET or POST, and what that does is: 0643

that describes the HTTP method that the form will use to submit the data.0649

It could be either GET or POST, and as mentioned, we are going to be working with GET, and so, that is what our forms will be using in this course.0654

But some of you may have used the POST method before.0662

The GET method--again, the way it works is by appending the name/value pairs after a question mark on the URL that you are sending the data to.0665

Additionally, probably the most important attribute is the action attribute.0674

That is the name of the script, or the URL of the destination script, that you are submitting your input to.0680

It is most likely go to be, for our course, in a PHP file.0687

That PHP file is going to be able to extract information from the URL query string, 0691

and then make it available to you so that you can use it within your script.0697

We are going to be talking about that in the next lesson.0702

Let's take a look at another form that has a bunch of different elements on it, to demonstrate the different elements that are available.0707

If you go to lecture_12, there is a form called inputExamples.php.0723

What this is: just an HTML form that shows some of the different options that are available as input elements, or input controls, on a form.0730

We have a basic text field where you can type any sort of text.0740

We have a password field, which is the same thing as a text field, except that it blocks everything out,0747

so somebody looking over your shoulder can't see what you are writing.0753

Now, that said, the password field does not actually encrypt any password you write in there.0757

It is just sort of something for when you are using maybe a public computer, and so forth.0760

There is the check box input control, which you can use to check different options.0766

There are radio buttons, which are used to select one option from a group of several options.0772

So, in this example, we can select either Yes or No.0778

There is a select menu, which is essentially a dropdown menu with different options to be selected.0781

There is a large text field, for example, where you can enter maybe comments--like if you have a Contact Us page on a website.0788

There are also what are known as hidden fields, which is information--a name/value pair--that is passed on to a script0800

that the user has no control over--essentially, the user is not entering any value.0809

It is not extracting a value from a field; it is hard-coded into the HTML.0815

Then, the other input controls are the Submit button (which is how you submit the form)...0821

There is also what is known as an Image Submit button, which functions the same way as the Submit button does.0827

It submits the form, but it allows you to use an image to click on instead.0831

There is also a Reset button, and the Reset button allows you to reset the form to its default values; so it clears everything you entered.0836

If we go ahead and type some data here again...select yes...and let's pick option 1, and we click the Submit button,0844

we can see that, in this case, this HTML form actually, just as we did for simpleForm.html, just submits the data to itself.0860

The destination URL for this form data is inputExample.php.0870

And if we go ahead and look at the source code for this (let's look at it in the text editor), it's a PHP file, but it only contains HTML.0877

We can see here the form tag that we had just talked about; and it has the two important attributes, method and action.0897

We set method equal to get, because the GET method is what we are going to be using, which appends stuff to the URL.0906

The action is inputExamples.php.0911

So basically, when this form gets submitted, all of the name-value pairs that are generated by the form 0915

are submitted to the URL inputExamples.php, which happens to be the same script.0920

Now, this script, though it's a PHP file, doesn't actually do anything with those values, but typically what is going to happen is:0926

your action is going to be to a PHP script; it is not going to be to an HTML file, because HTML files don't know how to handle the input data.0932

If we go back and look at the example, we see up here that it has appended all of the values 0943

and names that they are associated with from our form to the URL.0952

And again, we can use the Firebug console (sometimes you have to refresh the page to get it to show up), and we can see the GET request.0957

If we view the source, we can see the long string that was created, and it shows that, for every input control we had on there,0969

it has its name and then the value that it had at the time the form was submitted.0977

And maybe the more useful thing would be to click on the Params tab again, and that is going to show0983

the names and associated values from all of our input controls that were submitted when we submitted the form.0988

So, we have checkbox1; the value is checkedValue; password1--I had typed password; in the text box, I typed Matthew.0994

In the text area, I typed "Here is a comment"; so this all shows up--this is a useful debugging tool to see what actually is sent to your script,1005

so you can figure out where the problems are, if maybe you are having trouble processing script information.1018

Now, the other thing is: we can also submit the form, just to show you, using the input Submit button.1023

When we click on it, it does the same exact thing: it submits the form, 1034

and the browser itself generates the query string to append to the URL, which has all of the name/value pairs that the form represents.1039

And here, just for your use, I have listed a list of the common input controls used in HTML forms.1052

These are pretty much all the ones that you use; I think maybe in HTML5, they may have added some more options to this,1060

but these are the standard ones that have been used for years.1066

And as we had talked about, we had the text field, password field, checkbox, radio button, the select menu, which is a dropdown menu,1070

a large text field, and then hidden, two submit buttons, and a reset button.1080

The majority of these use an input HTML tag, and the way that they differentiate one type of input control from another is using the type attribute.1087

So, for example, the text field--you create the type attribute and set it equal to text.1097

The only two that don't use the input tag are: the select menu (and the select menu uses a select tag, and within it,1103

it has option tags, which describe all of the options that will be part of the menu); and then for the large text field,1114

where we enter comments that we want to send to the website, you use the text area tag.1120

So, as we mentioned, using the GET method, name/value pairs can be sent to a destination script,1133

using the HTML forms, or by manually appending a query string to the URL.1142

That is what we are going to talk about now: query strings and how they are formed and appended to a URL.1148

For example, we have a script test.php, and we want to submit to that form two name/value pairs; this is how we would do that.1154

This is something we could hard-code into, for example, an anchor link in your web page.1167

Or it is something that you could actually type into the browser itself.1174

What it does is: each name/value pair in query strings are separated by the ampersand, or the and sign.1178

And then, each name and value are separated by the equal sign.1186

And so, that is what a typical query string looks like.1192

And if you can think back on the other examples that we did, you were able to see that in the browser, as well.1194

Now, one thing to note is that query strings, because they are appended to the URL, are a part of the URL.1203

And as a result, they have to follow the syntax that URL's need to follow; and there is something known as URL encoding1208

that you need to do in order to make sure that the query strings that you append to a URL will work.1215

And for URL's, there are a couple of rules; one is that only uppercase and lowercase letters, decimal digits, 1223

hyphens, periods, underscores, and tildes are allowed as is in the URL, which means you can just type them straight in there without any problem.1233

Spaces, however, must be URL encoded or replaced with the plus sign--so they will be replaced with this.1242

And any other characters that aren't of this setup here or a space must be encoded, using the hexadecimal ASCII value of the character.1251

The way that is specified is by using a percent sign, followed by xx, 1264

where xx is two hexadecimal digits representing the hexadecimal ASCII value of the character.1270

So, for example, the name/value pair where we have person as the name and the value as Joe Smith, with a space in between Joe and Smith,1278

to properly encode that to be put in a URL, what it would do is: URL encoding replaces the space with a plus sign.1288

Additionally, let's say we have (and we'll learn about this in the next lesson) a name for an input element that is going to represent an array,1299

and so, it actually has two square brackets--an opening and closing square bracket--as part of the name.1311

Well, those don't fall into the category of the characters allowed, or a space, and so they need to be escaped or encoded.1316

The way they are is using the percent sign syntax.1324

It happens that, for the opening brace, the hexadecimal value is 5B, and for the closing brace, the hexadecimal value is 5D.1327

And so, grades[]=99, would be encoded as this here, which would be grades, the two hexadecimal values, =99.1338

And actually, if we go back to our original form simpleForm.html, we can see that when you use an HTML form1349

to submit GET data, the browser automatically encodes it for you.1364

So, for example, if we were to put as a text field...just put the opening and closing brackets and submit it,1369

and we look up here...well, sometimes--it didn't do it on this one, but sometimes--the browsers show it in user-friendly format,1379

but what it is doing behind the scenes is encoding it as a percent sign followed by two hexadecimal values.1387

Let's see if it shows up down here.1395

And actually, it properly shows up...what is happening is: Firefox is making it user-friendly, 1402

and so, it shows the opening and closing brackets as is, so when you look at the URL as a human, it makes sense.1408

But actually, what is happening behind the scenes is: they are being encoded.1414

And if you look at View Source, you can see, under the Request Headers section in the first line, it says GET simpleForm.html.1419

It has the question mark, text1= , and then it has text and the opening and closing brackets encoded as hexadecimal values.1432

So, you can encode URL's if you want to supply information to a script by a query string and do it manually.1453

You can do it manually and just type it into the browser or type it into your code.1463

But PHP also offers a built-in function called urlencode, and what that will do is: it will reduce the amount of errors that you make,1469

because you may forget the ASCII hexadecimal value for an open bracket, for example.1477

Well, by using the urlencode method provided by PHP, what that is going to do is: you supply it with a string 1483

that you want to be appended as a query string, and any characters (such as spaces or other characters like opening and closing brackets)1491

that need to be encoded--it does that for you.1500

The format for it is like a few other functions we have had experience with, like var_dump and print_r.1504

The function is called urlencode; you simple type urlencode, and it has a pair of opening and closing parentheses.1512

And within those parentheses, you include a string delimited by single quotes or double quotes.1519

What that is going to do is output the URL-encoded version of that string.1526

For example, if we call this method here, urlencode, with comments=Here, space, are, space, comments, 1532

the urlencode is going to return a string that looks like this.1539

What you can see is: it encoded the URL by replacing the spaces with plus signs.1544

Let's take a look at another script that demonstrates this.1552

Here is a script called urlEncodingTest.php, and it has a form that uses the GET method to submit data.1561

For example, I could type Matthew and click submit, and if we look up at the top of the browser, 1570

we can see the name associated with that text box is textSample, and it has been set equal to the value matthew.1578

That is how to do it in an HTML form; we also have down here a URL-encoded link, which if we click on it,1587

you can see that it says, "sampleText=Here+is+some+sample+text" which is the sentence Here is some sample text encoded.1599

Basically, the way we have done that is: this is a PHP file, and if we go and look at it in our text editor,1610

we can see at the top here that this is just the form that we use to demonstrate the GET method.1620

But also, what we have done here in PHP land is: we have created an anchor tag 1627

and set the URL equal to urlEncodingTest.php, which is the current script.1636

And we create a question mark, and then add the name of the name/value pair that we want to submit to this script.1643

And what we have done is: then we append...because urlencode outputs a URL-encoded string, we pass it the variable sampleText,1654

which is equal to this string up here, "Here is some sample text."1665

urlencode is going to replace all of the spaces with plus signs, and it is going to add it to this string.1669

Here, we just close out the anchor tag and name it URL Encoded Link.1674

So, if we actually go back and look at the file in the browser and view the source, we can see that1683

this link, which was generated in our PHP code section, has taken that sample text "Here is some sample text" and properly encoded it, using + signs.1696

That is an example of how the urlencode method works.1707

What it basically does is: it is a way to keep you from making errors, if you are trying to manually insert query strings1710

within some of your PHP files or HTML files.1719

Today's homework challenge is going to relate to that.1727

Basically, I just want to have you create a script called processName.php, and in that script, in the PHP section of the script,1730

I want you to create an anchor tag with an href attribute and append a query string to it, just like we have done in the previous example.1739

And whatever query string you decide to use, you can assign a name to it--you can call it name, for example.1752

You can hard-code that into your PHP.1769

And then, what I want you to do is use, as a value for name, your first and last names, separated by a space.1771

And then, I want you to use the urlencode method to properly encode your name: that includes a space.1779

Now, if it is done correctly, what is going to happen is: when you load the page and click on the link, and you refresh the page,1787

you are not going to see anything change in the page, because the form doesn't actually process any of the data.1796

But you will see, at the top of the screen, in the address bar, the question mark followed by name= ,1801

and it will have your name properly encoded with a plus sign for the space.1806

That ends today's lecture; thank you for watching Educator.com, and I look forward to seeing you next time.1813

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be expanding the material from last lesson, where we learned how to input data to a script.0004

Today, we are going to learn how to access that data from a PHP script.0012

Specifically, we are going to learn about what is known as the $_get array, which is how you access input that was passed to a script by the GET method.0018

We are going to talk about how we can use input controls to submit information to PHP in the form of an array.0032

We are also going to talk about how to output array values within strings, using variable interpolation.0040

What is the get array, is it is called? The $_get array is an associative array that is created by PHP every time a PHP page is requested by the GET method.0050

What it does is: it goes out, and it extracts any name/value pairs that were appended as part of the query string of the URL.0065

And it puts them into this array: basically, what it does is: for each name/value pair that is appended to the URL,0073

it creates a key, and it sets the key equal to the name of each name/value pair, 0081

and it sets the value associated with that key equal to the value of the name/value pair.0089

For example, if we have a text field, and we have it set at the name firstName,0095

when you submit a form containing that text field, whatever value is assigned to that text field is going to be associated with firstName.0104

So, it's going to be firstName=matthew as part of the query string.0114

What is going to happen is: PHP is going to go and create this get array that is always available in your PHP files.0119

And it is going to create a key called firstName, and it is going to associate with that key the value that you submitted.0128

So essentially, what it is going to be doing--if you remember from our lesson on arrays...0135

So, if we submitted...in the text field, if we type the text value, essentially what PHP is going to do 0157

is create a key, a name firstName in the get array and assign it the value value.0163

Let's take a look at a script, or a basic HTML file, that shows how some of this works.0176

What we have done is: we have created a basic HTML form that has one text field in it, kind of like we just talked about.0186

And what it allows you to do is submit your name--and actually, before we do that, let's look at the HTML code.0193

It is a form that uses the get method, because that is what we have been using.0202

The action, if you will notice, is something different from what we talked about in the last lesson; it's actually a separate file.0207

In this case, it's a PHP file; and now we are going to learn how to access that information.0212

So, this PHP file, processNameForm.php, is going to be able to use that information that we provide in a text field.0218

If we go ahead and I submit my name, it is going to go to processNameForm.php, 0228

and as you can see, it appended the name/value pair person=matthew to the URL.0237

And what I have done is actually just used the print_r function to output what the GET associative array looks like.0242

And, as you can see, the GET array contains one key and one value, and the key is person, and the value is matthew.0251

And if we actually go back and look at our HTML, we can see that, on the input tag for our text field, the name is person.0262

And so, person directly corresponds with the person key in the GET array.0271

Let's go look at the code that processes the form that processes the name.0282

It's called processNameForm.php, and basically, we have some PHP code here at the beginning that outputs what we had just showed you.0286

It just outputs the contents of the GET array.0295

Let's go ahead and delete that and do something a little more useful.0301

I've commented out a section of code here that is going to output a Thank You message, and it is going to quote the person's name listed on the form.0304

I have to get rid of these comment tags.0316

If we go back to our page and try a different name and click Submit, now what we have done is output a message0324

that says "Thank you," with the name submitted, Joe Smith, "for entering your name; you now have accessed PHP data for the first time.0334

"The sky is the limit," and I created a little link to return to the form.0341

Now, if we go back and look at the code here, all it did was: it has a couple of echo statements that echo some HTML code,0344

and then, one echo statement that references the GET array, 0353

and because the name of the text field which we submitted with the form was called person, we denote the person key and the GET array.0358

What that is going to do is go to the GET array, get the value associated with the person key (which in our case, I think, was Joe Smith),0369

and then it is going to output it--so it is basically going to add it to the output string.0377

That is an introduction into how GET works with simple name/value pairs.0382

Things can get a little more advanced: PHP has a nice feature,0395

in that it allows you to create arrays in the GET associative array that it provides for you.0399

The way you do that is: you provide, in the name attribute of different input elements, a name with opening/closing square brackets.0408

When you do that, and when you submit the form, what that tells PHP is that any name/value pair that has the name items,0422

for example, item...this one here...equals 1001--it is going to create a key called items, and then it is going to associate with that key an array.0433

And for every name/value pair that has the name items, it is going to add that value to that array.0450

A typical use of this is in select dropdown menus, where you can select multiple items from the list.0458

And the way that you access the values within your PHP script is: as we learned in the multidimensional array section of the array lesson,0469

you specify GET, and then, in this case, items; so that is saying "Get me the array associated with the key items."0481

And then, you specify a numeric index to access the different values in the array.0489

If we go and look at another form called indexArrayForm.html, we can see, we have a select box where we can select multiple things.0497

The way you do that is with the control key--Ctrl+click.0508

We can submit it, and what you can see here is: again, to demonstrate how the GET array is formed, you can see that 0513

(I'll blow it up a little bit), using the print_r statement, the GET array contains one key/value pair.0525

The key is named items, and it contains two elements--1001 and 3001--which are the ID's of the product that we selected.0533

They have the indexes 0 and 1.0544

Now, if we actually go and look at the HTML for the form, we can see that we have declared, as in the slide, a select dropdown menu,0546

given it the name items with the opening and closing square bracket, and then we have simply added option tags with different values.0557

What is going to happen is: when you submit that form, the browser is going to append to the URL (because we are using the GET method in this form)0567

items= , and then it is going to list the item ID of each item we chose from the list.0578

So, if we go back and look at when we submitted the form, you can see, in the top URL here, there is items listed twice in the query string--0584

items=1001 and items=3001, and because there are brackets associated with those items, PHP is going to know that 0597

that is going to refer to an array, and it's going to create an array with those values.0604

We just saw how PHP--you can use indexed arrays, or numeric arrays, in your forms; you can also use associative arrays.0616

For example, we can have two text input boxes, or text fields, and we can assign them a name like this,0625

where the array would be called person, and the key of the array would be called first.0637

We can also do it for another one with last.0643

So basically, what this is going to do is: when you submit this form, PHP is going to parse the URL.0647

It is going to create a key in the GET array named person, to which it is going to associate 0653

an associative array with the key first and the key last, along with whatever values were submitted to those corresponding text boxes.0663

One thing to note is that, unlike in PHP code (when we reference something in an associative array, you enclose it in quotation marks),0676

when you do this in HTML, you don't do that; you leave out the quotation marks; and PHP will know how to handle that.0691

Let's take a look at how associative arrays work.0701

We have a form associativeArrayForm.html, and it is going to allow us to input a first and last name.0713

We submit the form; we are going to do the print_r again on the GET array, and it is going to show you that the GET array0722

contains one key/value pair; the first key, or the only key, is named person, and it is associated with a data value,0733

which is an associative array that has two keys, first and last, and first is set to matthew; last is set to machaj,0742

which were the first and last names that were entered into the text field.0750

And so, if we go and look at the HTML form itself, we can see that we have two text input fields that we created.0757

And using the square bracket syntax, we typed person[first] to correspond to the firstName in the person array,0766

and then, this one right here corresponds to the lastName in the person array.0780

So, these are directly correlated to these in the GET array.0783

Now, if we go and look at the code...let's get rid of the print_r statement, and we can do something a little more useful than that.0793

This is going to demonstrate how to access the different values in the GET array that created an associative array called person.0805

One way we can do that is: we can declare a variable called person and set it equal to 0820

the value associated with the person key in the GET associative array, which, as we saw in our case, is this array here.0827

It contains a first key and a last key, and then the values associated with them.0836

And then, what we do is: we just create an output message to output the person's name, giving the welcome message.0841

And so, we have a couple of echo statements; here is just a welcome statement.0848

And then, because this is an associative array, we use the square bracket syntax for associative arrays 0852

to access the name associated with the key first, which was what was entered in the first text box.0858

And then, we also output the last name, which we access by the last key.0865

And if we go ahead and load this in the browser--let's try a different name...oh, I guess I didn't save it; let's try one more time...0871

You can see, it says Welcome, and then John Smith; and this John Smith...this is the first name 0895

that was outputted from the person associative array, and Smith was the last name that is part of the person array, as you can see here.0901

So, I have also created another script that shows more form input controls and how they work, similar to in the last lesson.0915

We go to echoForm.html (shrink this down a little bit): this is similar to a form we saw in the last lecture.0928

It has a text field, a password field, a radio button, a check box, a multiple selection box, text field, hidden field, and so forth.0938

If we go and put in some information like username, password, male, are you married, and then select a couple of our favorite RGB colors,0951

enter a comment, and click Submit...we are going to use the print_r function again on the GET array, 0963

and that is going to show you what was passed on by the GET method.0974

We can see that, in the GET array, there was a text field named username, and the value associated with it was username.0979

There is a password field, a text field (I misspelled password) that is associated with the value password.0986

Additionally, on this form, for the two questions sex and the check box "Are you married?" I have created an associative array0996

called personal info, and given it two keys, sex and married.1012

And if we go and look at the HTML for the form, we can see that, for the radio buttons, we have declared the name personalInfo,1019

and then put in square brackets the name of the key we want to assign that value to--in this case, sex.1036

And then, if we look down here at the married check box, we have assigned it the name personalInfo as well,1043

which means to put it in the same associative array as this up here, except it's going to use the key married.1050

And so, that is why, when we submit the form, it creates this personalInfo array.1059

Additionally, we have also created a numerically indexed array called favColors,1065

and what that was for, was for when you had the option to select multiple favorite RGB colors.1069

And so, what happens in that one is: as we had seen in the indexed array example before, for the select tag,1079

we give it the name favColors, and then follow it by the opening/closing square brackets, 1089

which tells PHP, when it finds any key/value pairs that have the name favColors, that they are going to be part of one array.1094

Because no index is specified, it is going to be a numerically indexed array.1102

And then, any options that are selected are added to this array.1105

So, in this case (let's go ahead and try again) we'll select blue and green, and we submit it.1109

We can see that it has added green and blue to the favColors array; and they have the index 0 and 1.1116

Additionally, the large text area Comments has the string that we included associated with it.1124

And also, down here, you can see, it has the value of a hidden tag.1131

We had a hidden input tag in our HTML; you go down to the bottom and look at it: input type, and we called it hidden.1136

We assigned it the name hidden, and then we gave it the value IP 192.168.1.1,1147

which may be some data that is of use to our script, but we don't necessarily need the user to see.1154

And so, when we loaded up the form and output the GET array, we can see that that hidden value,1160

even though it wasn't actually submitted by the user, does get put into the GET array.1169

Let's look again at the the processEchoForm.php.1184

What it does is: as the other files have done, it just uses a print_r statement to output the contents of GET.1193

But we can use it, again, to do something more useful.1201

In this case, we are just going to simply echo (and that is why it is called an echo form) all of the data that was submitted by the form.1206

As you can see here, we have a bunch of echo statements, in which we create an unordered list,1213

and for each list element, we output the value associated with each input field.1221

For example, for the username text box, we are going to use the GET array.1228

Access the GET array; give it the key username, which was the name in echoForm.html, which was associated with the username text field.1232

And we do that for all of the different input boxes; so we do it for password...1248

Additionally, as you can see down here, we had mentioned that we created an associative array, personalInfo, with the keys sex and married.1253

And as you can see here, the way we access that data from the GET array is using the double square bracket syntax used for multidimensional arrays.1262

And to review that again, what this first part here says is: Give me the value associated with the personalInfo key in the GET array.1272

That happens to be an associative array, and it contains different keys, and one of them is sex.1283

And so, this says to get the value associated with the key sex.1289

This one does the same thing, except it does "Get the value associated with the key married."1294

Now, down here, what we have done is: for the favorite colors, we look back at the HTML; we named it favColors with an opening and closing bracket,1300

which is going to create an indexed array in the GET array; PHP is going to do that automatically.1316

And what we can do is: we can output, in this case, the first color selected.1324

The first item in an indexed array always begins with the 0 index, if you remember.1328

And because this is a multidimensional array, we use the square brackets index again.1335

And this, again, says, "Give me the value in the GET array associated with the key favColors, which is itself going to be an array."1339

"And then, give me the first element in that, which depends on what we selected in the text box."1346

This just outputs the comments and hidden (remove this last comment and save).1354

If we reload the form, and let's pick red and green this time...female...password...New comment, and hit Submit, we can see the formatted output.1359

It says the username we entered was username; password was pawd; it outputs the sex of the user and whether they are married or not.1380

It outputs the first color selected, which in this case was red.1391

We change it, and then green and blue...it is going to output green, because green will be the first element added to the favColors array.1395

And then, you can see, it outputs, in a prettier format, the content of the comment input element and what was the value of the hidden input element.1407

So now, I want to continue on a topic that we have covered in a previous lecture, about variable interpolation.1423

And in this case, we are going to talk about how to output array variables within a double-quoted string.1428

We know that we can do that for, for example, integer, float, and other string variables.1434

We can include them within the double quotes of another string, and the echo statement will go ahead and replace the variable with its value.1439

But we can also do that for arrays; this is quite useful.1446

There is particular syntax for that: for indexed arrays, such as here, what you do is: 1450

you access the value of the array, simply as you would in your PHP code.1467

You simply type the variable name, which is a dollar sign followed by the variable name, 1471

and then square brackets with the integer index enclosed in between them.1477

And what that is going to do is replace this variable value with whatever the second value is in this indexed array.1482

That is pretty intuitive, because it's exactly the same way you would access it in PHP code.1494

Now, for associative arrays, it's a little bit different.1501

It's similar syntax, except that, if you notice, there are no quotes around the key name.1505

So, you access it in the same way you would in a PHP file, except you leave the quotes out.1512

This is known as the simple syntax; there is also a complex, or curly brace, syntax, which is used for outputting more complex things within strings.1520

And as we go through the course, we will find different, more complex things--for example, like object values and function output--to output.1530

But, if you want to use the quotes, and you feel more comfortable that way, you can enclose everything in curly braces and add the quotes.1540

Now, this curly brace syntax is also used for complex things--one of those being if you want to output a multidimensional array.1550

Let's say assoc was a multidimensional array; this is how you would specify that in your code.1566

Let's go take a look back at the process echoForm.php, and put some of this into action.1587

What you will see is: it is going to turn this...right now, we have three echo statements to output 1594

a list item that says username, and then outputting the username that was provided.1599

We can actually turn these three lines of code into one, and that is through variable interpolation.1603

Because this is an associative array, we go ahead and remove the quotation marks.1611

And if we go and load this page up, and submit it, you can see that it outputs the username, just as we expected it to before.1621

As you can see, it definitely makes the code a little easier to read--less lines to accomplish the same thing--and it's pretty intuitive.1641

You know that it is going to replace this GET[username] with whatever value is in the GET array, associated with the key username.1649

I'm just going to go ahead and quickly do this for these other values.1658

This is a multidimensional array, so we have to use, as mentioned, this special curly brace syntax.1670

And with curly brace syntax, we leave the quotation marks in.1675

The same goes for multidimensional arrays containing one dimension, or one of the arrays, as an indexed array.1696

I'm sorry, I forgot up here to get rid of the single quotes.1728

And so now, we have gone and changed all of those lines, which was three lines per list item, into one line.1731

And when we go ahead and load this page up again, it is going to output the same information, 1739

but we are making use of variable interpolation with associative arrays and indexed arrays.1744

Let's go ahead and...if we go ahead and submit it, we can see that everything outputs as we had expected from before.1752

That is how to make use of variable interpolation for arrays.1771

And you find that you will be using that a lot, throughout your PHP code.1775

For today's homework challenge, I am going to have you get practice with using the GET array.1781

You are going to be using it all the time in your PHP scripts, because you are constantly interacting with the user and receiving form input.1786

I want to have you create a regular HTML file that contains an HTML form, and just put it in the lecture_12 directory.1793

And have the form contain all of these different input controls.1802

And then, create another file, a PHP script, that is just basically going to echo the data submitted by the HTML form.1809

And make sure that, when you create this PHP script, you set the action attribute of the form element to whatever you named your HTML file up here.1818

And so...actually, the form element is going to be in the HTML file; make sure that you set the action 1832

equal to the name of the PHP script that is going to be echoing the data.1837

Then, what I want you to do is experiment with outputting and accessing values of the GET array.1843

So, use non-array names for your controls--for example, like name=text1; and just practice outputting those different values from your PHP script.1849

Then, change some of the controls, so that they have array names, like we talked about.1867

Maybe you will have a select dropdown box that will have the name...maybe it's states; and create it like that.1870

And do that for both the indexed array and the associative array variety, and practice outputting it.1884

And, when you output the value of the GET array, practice using what we learned in the last slide, 1889

which was variable interpolation that you can use with double-quoted strings to output the values of arrays.1897

Experiment with both the simple and complex syntax.1904

The simple syntax is just the variable name, and the complex syntax actually uses the curly braces around it.1908

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next lesson.1916

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be working on web application development, and we are going to be continuing 0004

to add features to our store web application, making use of what we learned in the last few lessons, 0008

as far as using GET data and input data from forms.0014

In today's lesson, there are a couple of things we are going to do.0020

First of all, we are going to review the last version of the web app that we had gone over, so that we can0023

see the changes that we are going to make, and see where they are coming from.0029

And then, we are going to have two new versions; we are going to have version 4.0 and version 4.1.0033

Let's take a look back at the last version of our web app, version 3.3.0039

And as you can see, it is our store, as we have seen before.0045

When you click on the links, you have item pages.0052

And the thing to notice, in particular, is that each item has its own page.0056

You can see here at the top of the browser, item 1002 in the store has its own PHP page called item-1002.php.0060

We are going to change that, so that you don't have a separate page to manage for each individual item.0069

If we go and look at the code again--let's look at item--1001.php.0076

If you remember, what it does is includes the catalog, which was our include file that has an associative array0081

containing all of the information about the items in our catalog--the name, the price, the description, the file extension, and so forth.0091

We include that, and then we give the current ID variable the ID of the item that we are going to be showing the page for.0100

Give the page a title; include the header and the footer; and then, what we had done on our last version was:0110

we created a new include file, itemListing.phtml, which basically included all of the HMTL and PHP code we used to output the item's information.0115

And basically, what we did is: we put that in one file, and we use that in each item's page.0127

So, item-1001.php, item-1002.php, and so on all included this.0132

And so, we are making use of code reuse; and today, we are going to go one step further and make it0138

so that, instead of having a separate page for each item which we include in itemListing.phtml, we are going to have0143

one page that we are going to use GET query strings to send the item ID of the item we want to view, and it's all going to be in one page.0150

Let's go and take a look at that; let's see what changes we are going to make.0160

So, the new version is going to be item 4.0, and what we have done in this version is: we are making use of GET query strings,0165

which, as you remember, is if you have the name of a page--the URL--for example, item.php, which is the page we are going to be creating today,0174

at the end of it you put a question mark with a query string on the end; I ran out of room, but then we put the item number on the end.0185

And so, what we are going to make use of that new functionality that we have learned about, about how to process GET data.0197

We are going to be adding a page called item.php, and what that is going to do is 0204

take the place of item-1001, item-1002, and item-1003.php, as well as itemListing.phtml.0210

Additionally, because on our home page of the store, we have links to all of the different items, 0222

we're going to have to alter the links on that page, because we are obviously getting rid of these pages, and so,0227

to link to them is going to be different; and so, we are also going to be editing store.php.0232

Let's go take a look at the code for these.0237

First, let's look at item.php: what this file does is the same thing as maybe item-1001.php in the last version,0241

except what it does is calls itself item.php, and what item-1001 had included in itemListing.phtml, which was here--item.php just has that all in one page.0253

So, as you can see, it includes the catalog--some new stuff up here--but what it does is: it loads the current item0265

(and we are going to get to more of that in a second) before it was hard-coded in the page, and then it includes the HTML header right here0274

and the HTML footer, just as before.0284

And this section in here is what was in itemListing.phtml; before, we had that included in each item's page.0286

Now, what we are going to do is: we are going to set it up (item.php), and we are going to pass it an item ID by a GET query string.0294

And when that page loads, at the beginning of the page (because now we know how to access GET data from PHP), 0302

we are going to grab from the _get array that we just learned about.0309

We are going to grab the value associated with itemID, which is going to be the ID of the item we want to view,0316

and we are going to set it to a local variable--in this case, currentItemID.0323

And then, what we are going to do is: after we have the item ID, we are going to use our item catalog,0329

which is in catalog.php, and we are going to use the item ID to look up the particular item that is being requested0335

and pull of the information about it.0343

Basically, this is an associative array; so when the user requests itemID 1001, we are going to go and pull out this array from catalog.php.0346

And so, that is what this line does, right here.0355

It goes into the item catalog, which is accessible because we have included catalog.php up here.0358

It uses the current item ID, which is passed in by GET, to load that item.0363

And then, here we set the page title using the current item and getting its name number from the associative array.0369

And then, down here is the same code as before that we had, except we are using a new variable currentItem.0379

And all this is doing is outputting the different information about the item, so here it is putting its name, the itemID, its price...0386

Down here, it is outputting the image, which is a combination of the item ID and the image file extension...and also description.0395

Let's take a look at this in action.0406

This is version 4.0, and if we go to store.php and we click on one of the links, if you can see at the top of the browser here,0409

in our address, we have item.php, and then we have a question mark indicating a query string.0419

And the name/value pair that we are passing in is itemID=1001.0425

What we are doing is passing to this script--we are saying we want to see the information for item ID 1001.0430

And we can do the same thing as this with the other links on the home page, too, by putting in item 1002, for example.0437

That is going to go out; it is going to load the information from the item catalog array, and then show it for item 1002.0446

We go back to the home page; you can see that it does that for all three of the different items.0455

Now, because we are using query strings, the links to get to the pages are different.0463

Whereas, in the previous version, on store.php, we had the links to each item's page coded as individual pages...0467

As I mentioned, each item had its own particular page; so in this case, item 1001--all of its information was contained0480

on its own PHP page, called item-1001.php; and as you can see, that was the same for item-1002 and item-1003...0489

Now, those pages don't exist anymore; so what we are going to do is: we are going to change those to an item.php link with a query string.0499

So, if we look at the new version of store.php, we can see that the links now have become item.php,0506

and you have the question mark to indicate the beginning of a query string, and then the name itemID equal to the item ID of the item we want to see.0514

And you can see, we have done that for both the item 1002 and item 1003.0526

One thing that we had talked about when we were talking about query strings was using the urlencode method.0532

That was a way to encode query strings on the URL, or append query strings to a URL in an encoded form,0538

so that they would follow appropriate URL syntax.0546

We haven't used that function here; and the reason is because here we know that this is a valid URL.0550

We know that there are no spaces, for example; there are no special characters that need to be replaced.0559

Typically, when you use the urlencode is when maybe we would, instead of having 1001 here, be passing in variable itemID.0566

Usually, any time you pass in a variable, you are not necessarily guaranteed as to what the value is going to be.0576

There could be some strings that need to be encoded in there.0581

So, in this case, if we had a variable, we would use urlencode, for example.0586

This isn't actually proper syntax, but it is just to demonstrate what it would look like.0594

And I just wanted to mention that we had talked about that; but the reason that we aren't using that now0600

is because we know that this is a valid query string.0605

That is all of the changes that we made to get to version 4.1; and again, this is what the store looks like, 0612

and all of our links have the query string with the item ID appended to them.0619

We are also going to add another thing to our web store, to make it a little more feature-rich.0626

We are going to be adding a checkout page.0633

And so, if we look at the change log from going from version 4.0 to 4.1, we can see that we are adding a checkout page0636

where a customer can enter billing and shipping information.0646

And after they submit, a customer will go and (I'll show you in a minute) they will submit their information.0649

They will be forwarded to a Thank You page that says "Thank you for your order," and it will output their shipping information that they had entered.0655

So, we're going to forward to a Thank You page.0663

One other thing we are going to do is: because this is a checkout page, we want it to be accessible anywhere on the site.0667

We are going to add a link to the footer, in footer.html, to this new checkout page.0673

We are going to be changing that.0677

So basically, we are adding two new pages: checkout.php and thankYou.php.0679

And we are going to be editing footer.html, and we are also going to be making some edits to store.css,0685

because we are adding some new tables that need special formatting or different formatting from what we already had available.0692

So, there are some minor changes to add, which we are not really going to go into and focus on the CSS.0699

Let's take a look at what this new source is going to look like--the store with this added checkout page.0706

We go to store.php; you can see down here, now we have a checkout link; and if you click on that, it is going to bring up a form.0714

It says, "Please enter your information to complete your order."0721

Now, we are slowly building up this store as we work through this course, and we are going to continue to work on this site in the advanced course.0725

So, this isn't a fully functional thing; but what it does is...0732

We are just starting to expand, so this form doesn't actually save your billing or shipping information anywhere.0736

But what it is doing, and the reason I have included it in this web application lesson, is: it is going to demonstrate how to access GET data0743

that is sent to a web server by an HTML form, because in the last few lessons, we went over getting GET input data from a query string,0752

and also from an HTML form; this is going to demonstrate getting it from an HTML form.0762

If I just type in some sample data here, and hit Complete Order, there are a couple things to note.0769

One is: if you look up at the URL, if you are able to see that, you can see that we are going to the link thankYou.php,0796

and there is GET data appended to the end of the URL that contains all the information we had entered in our form.0806

That is because our form uses the GET method.0813

You can see a Thank You message, and what we have done is echoed the information that I had just put, the shipping and billing address.0817

And the reason for that is: it is going to give us practice with accessing the GET array, the _GET global array, and outputting the data.0828

Let's actually take a look at the code.0839

Close some of these down and go to version 4.1...we are going to load up checkout.php and thankYou.php,0844

which were the new pages we've added, and also footer.html.0859

I'll start with footer.html, because as you saw, there is a link at the bottom of every page now that goes to checkout.php.0867

So, all we have done is edited our footer.html include file and added an additional link down here to the checkout page, which is checkout.php.0874

That is it--that is a pretty minor change.0884

Now, if we look at checkout.php itself, we have our usual include for the catalog.0888

We include that on every page; we create the page title and include the HTML header.0895

And then, what we have is the form--the HTML form that uses the GET method, because that is how we are going to access...0901

on thankYou.php, when we echo the information the user entered back to the user, we are going to access it by the GET array.0909

So, the form method we have chosen is GET.0917

The action, and where this form is going to submit the data to you, is thankYou.php.0920

And as you can see, it is just a table that has been created to give some formatting, and it has a text input field 0925

for all of the different information that a customer would enter.0932

And as you can see here, we have used the array syntax within the name attribute of all of the different input elements.0936

And what that does is tell PHP to create a customer array.0948

And in this example, it is going to create a key with the name firstName, and then it is going to associate with that key0952

whatever value was submitted on this text box.0960

So, when this form is submitted, we have a customer associative array that we can go to and access all of the different information in one spot.0962

And so, that is what this form looks like; and if we look at the HTML code for it, you can see the (I'll blow this up a little bit)0972

same form as we had just shown with the arrays as the names of all the different input elements.0988

Now, when we click Complete Order, again, it goes to thankYou.php, so let's take a look at that page.0997

thankYou.php...now, because it had information submitted to it by the GET method, by an HTML form,1003

we are going to access that information using the _GET array.1013

And basically, what we are doing here is just creating a short variable, because we are going to want access to1018

all of the information that was submitted on the form.1024

And instead of having to use this long name each time we want to access a different piece of data that was entered,1026

we can use the shorter variable name.1033

In this case here, we are taking from the GET array; we are loading from the value that was associated with the key customer,1037

which is, in this case, an associative array that has things like first name, last name, city, street, address, and so forth.1046

And then, when we go down here, put a little Thank You message.1054

And in this section right here, we are echoing the information that they submitted; 1057

and that is to get practice with accessing the stuff from the GET array.1064

As you can see here, it is just another table that we use for formatting; and in each of, for example, the table cells, we have output different information.1069

We have output the customer's first name, last name, street, apartment, and so forth.1080

As you can see, here we have used the curly brace or complex syntax within double quotes in an echo statement.1085

And that is in order to be able to access the value of this variable.1093

So here, we are accessing the value that is associated with the key firstName in the customerData array,1098

which, as we saw up here...the customerData array was taken from the GET array, which contains all of the information that is passed in.1105

And so, that is how the echoing of that form works.1118

That finishes our review of the different changes that we made.1126

For today's homework challenge, I just want you to go out and just try to get an understanding of what is going on, 1130

and understand how one of the nice things about using the GET query strings is: now, we have one page called item.php,1137

and that one page, we can use to display all of the items in the store, by submitting a query string with the item ID.1146

Now, before, we had three items, so we had three separate PHP pages to maintain; so, what this is going to do 1153

is improve our site maintainability, because we only have one PHP page to manage, item.php.1158

And just try and understand how the query strings work to enable us to do that.1166

Also, just look over the form that we had, the HTML form for the shipping information,1173

to look again at the syntax that we used for making sure that data submitted on the form is loaded into an array by PHP.1181

In this case, it was loaded into the customer array, and that was using this syntax in each of the input elements.1188

And again, that is just to make sure that you understand that syntax, because we are going to be using it a lot throughout the course.1203

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1215

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be covering what are known as expressions and operators.0005

Specifically, we are going to be going over what expressions are and what operators are.0012

Then, we are going to go through a number of different operators that are available (and operators are things like addition, subtraction, and so forth).0018

And so, we are going to have a couple of slides going over a number of different operators available in PHP.0025

We are also going to go over a topic known as precedence and associativity, 0031

which is like rules that apply when you do multiple operations at the same time.0036

What is an expression? That is part of what the lesson is titled.0042

Well, in PHP, an expression is anything that has a value; so literals have values, variables have values--they are all considered expressions.0046

For example, here we have three different literals: an integer, a float, and a string.0056

Those, obviously, are literal values; they have a value; they are considered expressions in PHP.0060

Additionally, variables have values; you set values to them.0066

Here we have an example of three different variables; we have a regular variable, an indexed array, and an associative array.0070

All of those have values, and they are considered expressions in PHP.0080

In this lesson, we are also going to be learning about operations, which are expressions in themselves, which means they have a value.0084

And then, in other lessons, we are going to be learning about constants, functions, and objects, all of which are expressions, as well.0092

And again, "expression" is just a synonym for something that has a value.0099

Operators work on expressions; an operator will take one or more expressions or values, which are referred to as operands,0105

which you may remember from your algebra days.0116

It performs an operation on those two expressions, those two operands, to yield another value for another expression.0119

The operators can be divided into categories, based on the number of operands they work on.0128

The ones that you are probably most familiar with would be something like an addition; you have 5+1.0133

It is what is called a binary operator; it has two operands--it has the 5 and the 1 that it operates on to yield a value.0138

In PHP, there are a couple of what are known as unary operators; and they are operators that work on a single value.0148

The majority of the operators we will see are binary operators for things like addition, subtraction, and multiplication.0155

PHP has one operator that has three values, known as a ternary operator.0162

But the majority of the operators are all binary.0168

The first operator we are going to specifically talk about is the assignment operator, and this is something we have already been using in our code.0174

We have already been using an operator, and maybe didn't even realize it.0182

An assignment operator is a binary operator, and as you know, it is used to assign the value of something to a variable, for example.0186

Basically, what that means in operator parlance: it is assigning the value of one expression to another expression.0195

For example, with the assignment operator (which we know is the equal sign), we have this expression here, 98.6, a float,0204

and we have this expression over here, bodyTemp, the variable.0211

The assignment operator says "Take this value and assign it to the variable on the left."0215

We have two expressions there.0225

Also, we have seen the array assignment operator, which is the equal sign followed by the greater than.0228

We have seen that in associative arrays where we have a key, and the way we associate a value in this case...0235

maybe Sunday it was 75 degrees; we associate the number with it using the array assignment operator.0241

And again, it takes the expression on the right-hand side and assigns it to the expression on the left-hand side.0247

Now, because both of these operators (the equal and the array assignment operator) are operators, 0255

and we learn that operators work on one or more expressions to yield another expression, 0262

these operations that we have seen up here (let me erase this) actually have a value.0268

It may not seem like it does, because normally you have something like 5+1, and you know that you have two operands and it yields a value of 6.0275

Well, this--because it is an operator, it has two expressions; it is a binary operator; it actually has a value itself.0284

This whole operation itself is an expression and has a value.0291

For the assignment operator, the value of the operation is the value being assigned.0296

And the way this might seem more apparent is: let's say we want to set a and b both equal to 5.0301

We have an expression like this, which is a legal statement in PHP.0315

PHP, with assignment operators, evaluates the one on the right first.0323

So, what PHP is going to do is: it is going to take this operation; it is going to assign the value 5 to the variable b.0327

And the value that that expression yields (which, for the assignment operator, is the value being assigned) is 5, is going to be assigned to a,0336

which makes sense, but it is essentially as if we had written it like this--if we had done it explicitly,0346

because when we assigned the value of a to the value of the assignment operation b=5, a gets assigned the value of 5.0362

There are arithmetic operators in PHP, as in most programming languages; and they have operators for all of the different typical arithmetic functions.0376

There is an addition operator and a subtraction operator.0387

You can do multiplication and division; and in PHP, like most programming languages, the multiplication operator is an asterisk.0390

So, if you want to multiply two numbers together, you would write it like...5 times 5 would look like that.0400

And the division operator is a forward slash; and so, if you want it to say 6 divided by 3, you would write it like this.0408

These four are all binary operators: addition, subtraction, multiplication, and division.0418

There is also the negation operator, which is a unary operator; that just takes the value of its operand and returns the negative version of it.0425

For example, if we have a=-5, this minus sign is the negation operator; it is saying to take the value of its lone operand, 5,0436

make it negative, and then the expression of value that that operation yields is -5, and so -5 is what is going to get set to a.0452

There is also another arithmetic operator known as the modulus operator, which is specified by the percent sign.0463

It is not as well known, but what it does is: it is basically a remainder function, so when you divide your numbers, it provides the remainder.0471

For example, if we have 7, modulus operator, 3, the result is going to equal 1; and the reason for that is:0480

if we divide 7 by 3 (go back to our elementary school math days), and we get 1, the remainder is 1.0487

And so, that is what this function outputs; that is a function to output remainders.0499

Let's take a look at a little code to demonstrate some of the different operators, which we will be able to look up from the Educator website,0505

basically just showing all of the different operators in action.0515

We are going to look at the HTML version of the code, because it's prettier and easier to look at.0519

For the addition operator, it is simply: as a binary operator, you take a value on the left and a value on the right.0526

It adds them together, and the result is, in this case, assigned to the variable a.0532

Here, if we have num=1, and then we add 1 to it, it is going to equal to, and a gets equal to 2.0538

All of the other arithmetic operators work intuitively the same sort of way.0545

For subtraction, if we have num set to 5, and we subtract 1 from it, the result of this operation is going to be the expression or value 4,0549

so a is going to get set to the value of 4.0559

And so on for multiplication and division: 2 times 2 equals 4; 6 divided by 3 equals 2; this is fairly intuitive.0562

The negation operator, which, as we mentioned before, is a minus sign, which is the same as the subtraction operator--0570

the way it is determined what it is going to be used as is the context it's in.0577

If it has two operands, it is treated as a binary operator, which means it's a subtraction operation.0580

Down here, it has one operand, the num variable; and so, this operator, the negation operator (let's blow this up a little bit) here--0588

the minus sign--says "Take the value of my one operand, num; negate it, and then set it equal to a."0598

So, in this case, a is going to be equal to -1.0608

And down here, we have this same modulus operation we had shown on the previous slide, 7%3.0611

That results in a remainder...when you divide 3 into 7, you get a remainder of 1, so a, in this case, is going to equal 1.0621

Just one thing to note is that the equation 7%3=1 is spoken "seven mod three equals one"; that is how you say it.0627

Like here, you would say, for division, "five divided by five equals," if it was a modulus operator, you would say, "seven mod three."0636

And so, that is how you speak it.0645

There are also what are known as the increment and decrement operators; what these operators do is:0650

they are unary operators--they operate on one value--and they increment or decrement the value of their operand by 1.0656

For example...first of all, they are represented by two plus signs and two minus signs together; this is the increment operator, and this is the decrement operator.0665

For example, we have variable i=0; right now, at the end of this statement, the value of i is equal to 0.0678

Now, we are going to perform the increment operation; we take the variable i, and we prepend it with the ++ operator,0687

the increment operator, which says, "Take my operand and increment it by one."0697

So, because i was equal to 0, and we have incremented by 1, at the end of this operation, i=1.0704

Likewise, for the decrement operator, it does the opposite: it subtracts 1; so this says, "Take the value of i and subtract 1 from it."0711

And again, that is two minus signs.0721

And so, because i previously was one, and we decrement it, i is now equal to 0.0722

There are kind of two operations going on at once here: i++, which...we will see there are actually two forms of the increment and decrement operators...0728

there is a pre form and the post form; this is the post form; they essentially mean the same thing, as far as incrementing or decrementing goes.0740

This says, "Increment the value of i."0746

It is essentially equal to if we had written the statement i=i+1; so, it's kind of an addition operation (we take the value of i; we add 1 to it),0749

and then an assignment operation, where we assign it back into itself.0759

Now, as mentioned, there is a pre form and a post form, and that is...either the operator goes before the variable, or it goes after the variable.0764

What that does is: because this is a combined operator of an addition and an assignment, whether you do a pre operator or a post operator0776

determines what value is yielded by this operation, because we know operations take one expression,0784

perform some operation on it, and yield another expression.0793

Well, with the pre increment operator, the value of the expression ++j is the value of j after it has been incremented.0796

So, if we assume j is 0 to start off with, and then we use the pre increment operator and set it equal to 1,0805

j is going to be equal to 1, because it has been incremented; and num is also going to be equal to 1.0813

Now, if instead we used the post increment version, where we have the operator after the variable name,0818

with the post increment operator, the value of the operation is the value of the operand before it is incremented.0826

So, right now, j is equal to 1 from the previous line where we incremented 0 to 1, the value of this operation,0835

because it's a post decrement, is j before it gets incremented.0843

So, num2 is actually going to get set to the value of j beforehand, which is 1.0848

So, num2 is going to equal 1; then j gets incremented, and j equals 2.0853

It is two different ways of using those operators.0859

Typically, you don't see the post one as often; typically you see the pre increment one, because it's a little less confusing.0864

When you use the post increment operator, I personally don't like to use it in my code, because it makes things a little less intuitive.0874

It adds some complexity to your code, because you have to think, "Well, is this setting the value before I've incremented it, or after it?"0882

So, in general, you don't see the post operators that much.0888

The thing that we will be using these operators for, mostly, is when we get to loops, which are ways to repeatedly go over lines of code.0894

Basically, they use a counter, and we use these pre increment operators 0904

to continually add one to the counter each time it goes through the loop, for example.0909

If we look at another page that demonstrates some of these operations, we can see some of the same things that we went over here.0915

We have a variable num=1, and we pre-increment it; the value of num is going to be incremented, so num is going to be equal to 2.0924

Then, that value is going to be set to a, so a is going to be equal to 2.0933

We reset the value of num to 1, and then we set a equal to the value of the post increment operation on the variable num.0937

Well, the value of the post increment operation is the value of the variable before it's incremented,0947

so a is going to get set equal to num, which here is 1, so a is equal to 1.0952

Then, num is going to be incremented, so num equals 2.0956

So here, in this one, a and num end up having the same value at the end of this statement; here they have different values.0959

This, likewise, applies for the decrement operators, as well.0967

So, for example, if we have num=1, and we do a pre decrement on it, both a and num end up having the value of 0.0970

Now, with the post decrement operator, it's just like with the post increment operator.0981

The value of this operation is the value of num before it's decremented, so a is going to be equal to 1, because that is what num is set to.0985

And then, after num gets decremented, num gets set to the value of 0.0995

Those are the increment and decrement operators.1000

There are also what are known as combined assignment operators, kind of like what we just saw with the increment operator.1006

PHP has them for each of the different arithmetic functions, so they each have the corresponding combined assignment operator.1013

For example, the addition combined assignment operator is a + followed by an equal sign.1022

This is the one for subtraction, multiplication, division, and modulus.1026

Basically, it is kind of like when we had i++, we said that was the same as if we did i=i+1; that is kind of how these combined assignment operators work.1031

So, if we have num+=10, it is the same as saying "num is equal to the value of num, plus 10..." 1050

What it does is adds 10 to whatever num is, and then reassigns the value to that variable.1063

It is kind of like the increment operator, except that here we have 10, and the increment operator always increments (or decrements) by 1.1072

Here, with the += operator, we can add however much we want to the variable.1080

This assignment is equivalent to this; and again, it's a combined assignment operation, because the first thing you have1089

is an addition operation that occurs: you take the number, and you add 10 to it.1095

The result of that--the value of that operation--is then assigned back into num.1099

Here are some more examples: if we start off with num=10, and then we do num+=10, at the end of this statement,1104

the value num is going to be equal to 20, because we have taken num's value, which was 10, added 10 to it, and reassigned it back to num.1112

Now, if we use, for example, the multiplication combined assignment operator, this says, 1122

"Take num, multiply it by 5, and then store the result of that back in num."1128

So, up here, num was equal to 20 at the end of this statement, so 20 times 5 is 100; so at the end of this operation, num equals 100.1134

A similar pattern follows; if we do num and then use the combined division assignment operator,1144

it is going to say, "Take the value of num (which is 100), divide it by 4, and set that back to be the value of num."1151

So in this case, num equals 25.1156

And then, the modulus operator--the same way: it is going to say, "Take the value of num (which is 25); mod it with 6;1158

and store the result back in num," and just to show the mod operator again: you do...6 goes into 25; we get a remainder of 1.1166

So, that is why this is equal to 1.1176

We have a page that demonstrates this as well; and this page kind of echoes what we have just done.1180

It shows how all of these look in code; we have a variable name, and then here, we have done the += operator.1188

That is going to result in the value of num, incremented by 10.1196

Here we have the -= operator, which is going to say "subtract 10 from the previous value of num and set num to that value."1202

So, num is going to be equal to 1 here.1208

Here, we see the multiplication combined assignment operator again; so it is going to say, "Take num and multiply it by 20."1211

So, num is going to be equal to 20.1215

Here we divide it by 4; num is equal to 5; and then, mod...you end up with num=1.1217

Now, we are going to talk about string operators: there are two string operators.1230

Well, it's one string operator known as the concatenation operator, and then it has a combined assignment version, just like the arithmetic operators.1236

The concatenation operator is simply a period, and it is an operator that is used to combine, or concatenate, two strings together.1245

It is a binary operator; so here we have the binary operator, the period.1256

And it has two operands: on one side is hello--the string literal hello; on the other side is world.1260

And this operator says to take these two values, these strings and concatenate them together, and the result is the string concatenated.1268

So, the message (at the end after this concatenation operation occurs) becomes the literal "hello world" where they are all combined into one string.1277

You can use this with both literals and variables.1292

For example, we could create a variable called day and set it equal to Monday, and then we could create a variable that's going to hold a message.1295

We started off with a string literal, "Today is", and that is one operand of the concatenation operator.1303

The other operand we can set to the variable day, and what that is going to do is concatenate these two strings together.1311

It is going to take "Today is" and combine it with the string that day represents, which is Monday, 1318

and output that as one string, and set it equal to message.1324

So, at the end of this, message is going to be equal to "Today is Monday."1327

Now, just like the other operators, the arithmetic operators, there is a combined assignment version for this one, too.1333

That is this here--the .= ; and basically, it is just like how the arithmetic ones work in that, if we have begin.=end,1339

that is saying, "Take the variable being, concatenate it with end (the operand on this side of the operator), and then assign that back into begin."1349

Let's take a look at a page demonstrating this.1364

This demonstrates the two examples that we saw: we have a string hello, and what we have done is saved it in message.1370

And then, we have taken the variable message, which is equal to the string hello, and we have concatenated it with the string literal world.1380

So, at the end of this operation, message is equal to the string literal hello world.1388

We could also do the same operation using a combined assignment operator, where if we set message equal to hello,1394

as we did up here, instead of having to write a full expression like this, we can just do .=world.1400

What that is going to do is just concatenate the world string to the string that message already is, which is hello.1406

And so, again, at the end of this, message is going to be equal to hello world.1412

Now, one thing I want to talk about to finish up the lecture is a topic known as precedence and associativity.1421

Basically, all operators have assigned to them a precedence and an associativity.1428

What those are for is when you have multiple operations occurring in the same statement.1433

For example, this statement right here has two operations: it has a multiplication operation, and it has an addition operation.1438

When PHP sees that, it has to have rules as to which operation it proceeds with first.1449

It could go left to right and say, "OK, I'm going to do 5 times 6 first; the value of that is 30, plus 2, and the value is equal to 32."1454

It could go the other way and say, "6+2 is 8; 8x5 is 40."1463

Well, the rules in PHP are that multiplication has a higher precedence than addition.1469

So, when those two operators occur in the same statement, the one with the higher precedence, multiplication, gets completed first.1475

It is sort of the same thing as if we had written this in parentheses here.1482

The value of this expression is actually 32, and not 40.1485

And actually, if you go...I have a link on the homework challenge to the PHP website and the PHP manual; 1492

there is an operator precedence page, and what it does is: it lists all of the different operators, and most of these we haven't seen yet,1499

which you can just ignore for now.1505

And it ranks them in decreasing precedence; for example, as you can see, multiplication and division are at a higher level than addition and subtraction.1507

So, as we can see in the last example, multiplication happened first.1521

Now, what happens then, and the way this chart works, is that everything on the same line has the same precedence.1527

So, what if you have two operations that are occurring in the same statement where both operators have the same precedence?1533

Well, then you defer to what is known as associativity.1541

What that does is determines, "If you have operators in the same precedence, do they get evaluated left to right or right to left?"1546

So, go back and look at the slide here: the multiplication sign and the modulus operator both have the same precedence.1554

In order to decide which one gets operated on first, PHP defers to the rules of associativity.1566

The associativity for these operators is left, which means they get operated from left to right fashion.1572

So, what is going to happen is: 3 times 3 is first going to get multiplied, and then it's going to be mod-ed with 2, 1578

as opposed to the other way around, 3 mod 2 times 3.1586

The result of this is actually 1 and not 3, because 3 times 3 is 9, and if you divide it by 2, the remainder is equal to 1,1594

as opposed to 2 goes into 3, remainder of 1, 1 times 3 is 3.1604

This demonstrates left associativity.1609

Now, as we saw in a previous slide, the assignment operator is right associative; so when we have a=b=5, this statement contains two assignment operations.1614

It has two assignment operators; they have equal precedence; so how does PHP decide which operation gets performed first?1630

Well, the associativity rules say the assignment operator is right associative, so the right one is going to get performed first, 1639

and then move to the left, so then the left one will be operated.1646

As we saw before, b=5 gets operated first; that assignment operation occurs, 1651

and we know that the value of an assignment operation is the value that was assigned.1655

This one occurs first, and then that value was assigned into a; so the assignment operator is an example of a right associative operator.1661

Now, one other thing that you can do, which you may remember back in math days, is force precedence using parentheses.1672

So, as up here, we had seen that, since multiplication has a higher precedence, it gets evaluated first, so we have 5x6 is 30,1680

and we add 2 to get 32; if we wanted to do reverse and add 6+2 first, and then multiply times 5,1688

we can force the precedence by adding the parentheses.1695

What that is going to do is tell PHP, "let me do what is in parentheses first: 6+2 is yielding 8; then multiply that times 5," so that is how we get 40 here.1698

The same way for this other operation: because, in this case, the multiplication and modulus operator have the same precedence,1707

associativity determines which operation occurs first, and associativity for these operators is left, so multiplication would go first.1716

By adding the parentheses here, we are saying we want to do this operation first; so 3 mod 2 has a remainder of 1, so it's equal to 1.1725

1 times 3 equals 3; so now, the value of the equation changes.1733

I have some examples of that, as well.1740

Basically, this is just a review of what we talked about; and we talked about precedence, saying that operations with higher precedence execute first.1748

In this case, which is a little bit different and shows the importance of precedence (because normally we read left to right,1758

and we would think this operation occurred first), in this example, multiplication has a higher precedence, so 2x3 is executed first,1766

which is equal to 6+5, is equal to 11; not 21, which would be the case if we added 5 and 2 and got 7 and multiplied it times 3.1773

Now, this example down here demonstrates associativity; again, the modulus operator and the multiplication operator1782

both have the same precedence, so the rules of associativity apply, 1788

which say the leftmost operation gets performed first, and then it proceeds to the right.1792

In this case, 11 mod 3...3 goes into 11 three times with a remainder of 2, so we get 2 times 2; this results in num being equal to 4.1797

That is not 5, as if we had done this instead--if we had done the multiplication operation first.1809

For example, if these were right associative operators, we would have 3 times 2 is 6; 11 mod 6 is equal to 5.1817

And so, you just want to note that these have left associativity; 1827

and as we talked about before, some operators, like the assignment operator, have right associativity.1830

And again, you can use parentheses to force precedence; so these examples that were shown above are now shown with parentheses,1836

to have them operated a different way: in this case, we can get the value to equal 21 by forcing the addition operation,1843

the lower-precedence operation, to happen first.1849

And then here, whereas the multiplication has the same precedence as the modulus operation,1852

but those operators are both left associative, we can force the right operation to occur first with parentheses.1859

For today's homework challenge, what I would like you to do is to go out and take a look at this link.1870

It's on the PHP manual, and what it does is shows you all of the different operators that are available in PHP.1874

And you can, like I said before, ignore the ones that we haven't covered yet, but you can see where all the different operators rank,1882

because when we eventually start writing arithmetic functions, and doing calculations, it is going to be important to know how they work.1889

And so, here, you can just see how the precedence works, and you can see that multiplication and division and modulus are higher up1897

in precedence than the plus or the minus or, in fact, the concatenation operator, as well.1904

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1911

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be continuing development of our web store application.0004

We are going to be adding a bare-bones shopping cart that is going to make use of the arithmetic operators that we had learned about in the last lesson.0008

In today's lesson, we are going to do a couple of things.0016

We are going to just quickly review what the last web application version was, and the features that it had,0019

so we can see the changes that we are going to progress to.0025

And then, we are going to make two updates to our web app; we are going to have a version 5 and a version 5.1.0027

Let's take a look at...this is web app version 4.1, which was the last version we worked at.0034

That is where we had added a checkout page where you can add your name and so forth, and submit it,0041

and it will say "Thank you" for submitting your information.0050

We also have the item.php that uses the query strings, so we have one page for all of our items.0054

That was done in the last two versions.0063

In this version, as mentioned, we are going to be adding a shopping cart page.0066

It is not going to be a full shopping cart, because we don't have all the tools to really do that yet.0069

But it is going to be part of our process of building up to that.0075

We are going to make a static shopping cart page, which is the page where you go, and it lists all of the items in the store,0079

and the user can select how many they want and then click Check Out.0085

What they are going to do is have a page where they can go and do that, and when they check out, it's going to forward0089

the items they selected onto the checkout page, which before had the shipping information form and billing information form.0098

When it gets passed over to that page, it is going to calculate the total and output it at the top of the screen.0107

It will say "your total was this," and it's going to ask you to please enter your shipping and billing information.0111

So, we are going to be altering the checkout page a little bit, in addition to creating a new page.0118

The new page is going to be called viewCart.php; we are going to be altering checkout.php, as well as the footer and the CSS.0124

In the footer, we are basically updating to add a link to this new Cart page.0132

Let's take a look at what this new version looks like.0138

This is version 5.0, and as you can see, we have the links at the bottom, and we have the new link down here.0142

Everything else is the same, but we have the link View Cart.0150

What it does is: it lists all of the items in the store and their price, and then this is an HTML form 0153

that uses the GET method to pass the input along to the next script.0158

And what it allows you to do is set a quantity; so let's just say we want to get one of each of these.0164

We hit Checkout; this script calculates our total--we altered the checkout script so it calculates your total; it says "Your shopping cart total is this."0171

And then, it outputs the same form that we had before, for example, to output your shipping information.0180

Let's take a look at what is going on behind the scenes in this Shopping Cart page.0187

If we look at the HTML source (let's make this a little bit bigger), what we have done is: in the middle of the page 0194

(this is the content section of the HTML page), we have added a title, and we have created a form.0211

And the form uses the GET method; it is going to pass the data you entered, which is the quantity of items desired,0219

to checkout.php, and this is just a table that formats what this is going to look like.0225

As you can see, what it does is: it has a row in the table for each item.0238

This HTML isn't the prettiest HTML, because to do that with PHP, you kind of have to get fancy with new lines and tabs and so forth.0242

So, sometimes it doesn't always come out the nicest.0251

But what it does is creates one row in the table for each item; and so, we have a row for item-1001...0254

It lists...this is a link, and an image to the item's page; so you can click on 100% Cotton T-shirt, and it would take you to that page.0262

It outputs the price, and then it outputs a text box that is where the user can enter the quantity that they want for that particular item.0271

What we are doing is: we are using this array syntax again within the name attribute of the input text box.0280

We are creating an array...we are going to have PHP, when this form is submitted, create an array called items.0288

It is going to be an associative array; the key of the array is going to be the item number.0297

So, for each item that we have, it's going to create a key and value in the items array,0303

where the key is the item number, and then the value is going to be the quantity that the user selects.0310

And so, when the form is submitted, it is going to pass, on the checkout.php, an array with each item as the key,0316

and then, as the value for that ID, it is going to have the quantity.0329

Let's look at the PHP code behind this: this is the beginning of the form, which is just HTML, and down here is where it's for the first item, item-1001.0333

And what we have done is gone through and manually created a row of information for each item.0349

What we are going to learn, as we progress in the course and learn about loops and stuff like that:0355

we are going to be able to do this repetitively and only have to write this code once.0358

But because we are not there yet, we have gone and manually output the information for each item; and this is how it looks.0362

Basically, for item-1001, we set the current ID of the item, or we set a variable called currentID; so for this one, we are going to output the data for item-1001.0370

Then, we load the associative array that contains all that item's information from the item catalog, which is in our include file, catalog.php.0380

We are saying, "From the item catalog, give me the associative array associated with ID 1001, and store it in currentItem."0389

And just to make things easy, we are going to create some short versions for the different values that we are going to pull from that items array.0399

We are going to get the name, the price, and the image file extension, and we are going to store them 0408

in these variables curName, curPrice, and curExt to represent those three things.0412

Then, if we look at the page, we can see there are three columns; 0420

and the first one is a small picture of the item and a link, and then the price and the quantity box.0424

So, the first thing we are going to do is output this image and link; and that is what this section of code does, down here.0432

In PHP code, we have a bunch of echo statements, and they are outputting the link to the item page.0440

And we have it set up so you can click on the image or the item's name to go to the item page.0450

Basically, the way that works is using GET query strings, just like on our homepage, store.php.0456

We had updated to use query strings to look up different items, so this would be item.php?itemID=1001.0460

Well, that is how we are going to do that here: we are going to do the same thing, except we are going to create them dynamically.0470

So, we are going to output using double-quoted strings, item.php, a question mark, and we are going to say itemID=.0475

And then, if you notice, here we have our concatenation operator, which we just learned about, as well.0485

And to this, we are going to concatenate the current item ID, which would be 1001, and we are going to urlencode it.0491

And as mentioned in the last web application lesson, we didn't use urlencode function before, 0499

because we were hard-coding the value, and we knew that it was a safe value.0506

But typically, any time you are going to be outputting variables that may come from other sources 0509

(maybe it comes from functions other people have written if you are programming on a team, for example),0515

this will ensure that anything that gets output will be output appropriately.0519

That is just good practice; so it is going to output the item ID, so that is going to create the link to the items page.0522

Here, we have an image tag where we are dynamically creating the image name.0531

The image name for each item is the item's ID with the image extension as the end of it, so it would be like 1001.jpg.0535

And then, down here, so that things look neater, we separated the links out; we made one link around the image tag,0546

and then we also created a separate link just for the name.0553

So, if we look at the body of this link tag, it's currentName.0558

So, this would be the body of that link tag; and then, this image is a link, as well as an image.0564

So then, in the next column over on the table, we are going to output the current price.0577

And then, the key part is: we are going to then create a text box, and as mentioned, we are going to, as we saw,0582

use the name attribute to have PHP create an array when the form submitted.0591

It is going to create an array called items, and you can see the square bracket notation.0598

What we are doing is dynamically inserting the current item ID; instead of hard-coding it in there, 0602

we already have it listed up here in the top of our file.0609

And that is the point of the variable: so that we can refer to it all at once, and if we need to change it, we only change it in one spot.0614

We could just hard-code in here like this--erase this and just do 1001--but then, every time we have to change the item on the page,0619

we have to go through and manually edit it.0628

This way, we can change things in one spot; so that is another example of code reuse.0629

That outputs a text box with a quantity, and we set it up with an initial value of 0.0635

And we repeat this process three times for item 1002 and item 1003, so it creates three rows in the table.0641

And again, we do this manually, because we don't know about the loops and things so far in the course.0651

But later on, we are going to be able to automate this, where we can write this code once, and it will loop through three times for each item number.0658

We don't actually have three sections of code; and that is good, because since I have typed this section of code in here three times,0665

there are three chances for me to make a mistake again; so that is another important thing that we will get to about code reuse.0671

Especially if you have something that recurs over and over, you only want to have to write it one time.0679

That is what the shopping cart looks like; and as mentioned, when you go to checkout, you can see,0686

at the top of the page, in the URL, it has the items array listed as name/value pairs.0696

It has items-1001=1; items-1002=1; those are the quantities we selected.0701

And so, checkout has changed; before, when you went to check out, it just showed the form (this was in the last version).0707

Now, when we go to check out from the new cart, it's going to have a little message that is going to say what the shopping cart total was.0715

Let's look at checkout.php, which has been changed, because we are going to be doing the calculations for the shopping cart in there.0721

The first thing we do in all our pages is include the catalog.0728

And then, we are going to create a short variable for the items array that was passed from the View Cart form,0733

which, again, has one key entry for each item ID, and then the corresponding value to that key is the quantity selected by the user.0739

This items is an associative array with ID as the key, and the value being the quantity chosen.0750

Now, we are going to make use of these arithmetic functions that we learned about.0756

We are going to start off with a variable called currentTotal; it is going to represent the current total; and we are going to set it to 0.0760

You should always initialize your variables to a default value.0768

And in this case, because we want our total to start off at 0 (we are going to add up to it as we add items to it), we give it the value 0.0773

And then, here, we have three steps where we manually go through and pull the price for the item that was selected 0779

(for example, 1001) out of the item catalog; we look it up in item catalog, pull its price out, and then multiply it times the quantity the user entered.0789

So, you can see, for item 1001, we go to the itemCatalog array in catalog.php; 0798

we select the 1001 element; and then we select the price value from that.0805

And then, what we do is: cartItems is the short form of this GET query that we had at the top of the screen, and we are going to say,0815

"Multiply it times the value associated with the key 1001," and as we mentioned, 0826

the value associated with the keys in this cartItems array is the quantity.0831

So, this is basically saying, "Take the price of the item 1001; multiply it times the quantity 0835

that was chosen by the user; and then add it to the current total."0841

And here, we are making use of the combined assignment operator.0844

So, instead of doing curTotal plus this equation right here, and then setting it equal to curTotal,0847

we can just use the += operator that automatically is going to take this right here, perform the operation, and add it to current total.0855

This is updating current total, so now current total is going to reflect the amount of the first item on the list, item-1001, and what quantity was chosen.0863

And then, we go through and do the same thing for item 1002 and 1003.0878

We simply look up the price for each one, and then multiply it times the quantity that the user selected on the form.0882

And we use += again, and what that is going to do is: that keeps adding it to the last value of current total, so it adds up.0888

And once we get to the end of this line here, we are going to add up the current total of the cart,0895

which is the prices of all the items, multiplied times the quantity selected, added together.0898

Now, what we have done is added a little message at the beginning here of checkout.php, which wasn't on the last form,0903

that just outputs the total that we had calculated, which is going to echo current total.0910

And then, after that, what it does is goes and lists the same shipping and billing form that we had before.0916

And so, that is what this little message is up here; this is the new message that has been added.0924

The calculation is done in checkout.php, and we have made use of our arithmetic functions.0928

That is version 5.0 of the store; we are also going to make, in this lesson, one more modification to the web store.0934

We are going to call it version 5.1; and what we are going to do is: on the previous version, when you checked out0944

(actually, it didn't do it on this current version), we have our total that has been calculated from the View Cart page.0956

And then, it brings us to the shipping page, and we enter our shipping information.0967

And we go to Complete Order, and it says, "Thank you; your order has been completed, and will be shipped to..."0978

What would be nice is: when you are done with your order, and you have completed your order, you would like to see the final total again.0985

I mean, typically, when you go to a website, they say "Thank you for your order," and then they show you a total.0992

So, we are going to make it so that we can output the total on this Thank You page, as well.0995

In version 5.1, what we are going to do is: when we view our cart to add an item to it and checkout, there is the total being output, and then...1000

And now, when we do Complete Order, and we go to the Thank You page, it is going to say the same thing:1028

"Thank you; it has been shipped to [the address we entered]," but it is also going to say,1033

"Your order has been completed with a final total of $644.98."1036

What that does is: we are going to use a technique of hidden input fields in order to pass...1042

Basically, what we are doing is receiving the total on checkout.php, and we are going to forward along to Thank You.1047

So, in version 5.1, as said, we are going to add a hidden input field to checkout.php,1054

and that is going to take that total that was calculated at the top of checkout.php, and it's going to forward it on to the Thank You page.1061

When the user submits the shipping form--when they enter in their name and their address--it is going to also forward along the total.1068

And then, that way, thankYou.php has access to that variable.1074

We are going to make modifications to both checkout.php and thankYou.php.1080

I'll pull up the 5.1 version; so version 5.1...we are going to look at checkout and thankYou.1088

On the checkout page, it is all the same as in the last version, except, at the very bottom of the shipping form, we add a hidden input field.1103

We have decided to name it orderTotal; and then, what we are going to do is: the value, currentTotal, that was calculated1115

all the way up here at the beginning on these lines--we are going to forward it on.1123

The way to do that is through this hidden form.1130

So, when the user submits this shipping form, it is going to submit a name/value pair1132

where the name is orderTotal and the value is going to be the current total that was calculated.1138

And so, then the thankYou.php has to be ready to accept that total, or be able to print it out.1144

And so, what we have done is created a short variable where we get the value associated with the orderTotal name1152

that was the name of the hidden input tag, and in this case, it's going to be the total value that was calculated.1161

We are going to set it into this variable orderTotal, just as a shorter version, instead of using this longer GET version.1166

And now, we have changed the output message a little bit: it says, "Your order has completed with a final total of__," and we output the order total.1174

And then, the rest of it is just outputting the address, just as before.1182

What that has done is: that is a common technique that you can use for when you have a form or a process of forms1187

where data is going from one form to the next--sometimes you need to pass that information along,1196

because HTTP is a stateless protocol, and it doesn't know about what happened before.1199

You can continue to pass things along by using hidden input fields.1205

For the homework challenge, I just want you to look over the arithmetic operations that we did at the beginning of checkout.php,1211

so you can see the use of the combined assignment operator and the multiplication operator,1219

and just make sure that you understand what is going on in the material from the last lesson--you can kind of see it in action.1223

And then also, make sure you understand how the hidden input element can be used to forward input data1230

that is received at one script--to forward it on to another, so you have a chain of events as we go from View Cart to checkout.php to thankYou.php.1236

We can pass that order total along.1244

That ends today's lesson; thanks for watching Educator.com--I look forward to seeing you at the next lesson.1247

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be talking about two new data types 0004

that we haven't talked about before, the boolean data type and the null data type.0007

As part of talking about the boolean data type and the null data type, we are also going to go over what are known as comparison operators.0014

We are going to be introducing a new class of operators; previously, we have worked with arithmetic operators0021

and the concatenation operator; we had introduced those a few lessons ago.0026

We are going to learn a few more operators today, and then we are also going to briefly talk about 0030

coding conventions, as it relates to these two data types.0034

What is a boolean data type? Well, a boolean data type is one of the four scalar data types in PHP.0040

We have worked with three of them already: the integer, the float, and the string.0046

The boolean is the fourth scalar data type, which is a data type for representing single values.0050

A boolean is used to represent a truth value, meaning it's either true or false--it's one or the other.0057

Booleans, or bools, as they are commonly referred to, 0063

are used extensively throughout our code, and we are going to be using them, from this lesson onward, all the time.0068

They are the output of comparison operations; I mentioned a minute ago, we are going to be learning about the comparison operators in this lesson.0073

They are also the output of many functions, and so we are going to be dealing with these boolean values all the time.0080

In PHP, there are two boolean literals that you can assign to a boolean variable, and they are the special key words true and false.0086

True and false are treated in a case-insensitive manner by PHP, so you can do them in any case that you want to.0098

But typically, the convention is to do them either all uppercase or all lowercase, like this.0105

Let's take a look at a sample PHP file called booleans.php that demonstrates the use of boolean variables.0111

The first thing we are going to do is do a var_dump function on both of the boolean literals: the boolean literal true and the boolean literal false.0122

That is going to show you 1) how to specify the boolean literals (which is--you just write them in the code in all capital or lowercase letters--0131

just as is, and the PHP Interpreter knows to interpret them and knows they are not strings or anything like that--they are special,0141

reserved words), and var_dump, as we know--it outputs the type and the value of whatever piece of data is passed to it.0147

So, when we var_dump on the true value and the false value, we should see that it's a boolean, and we should see that they're equal to true and false.0156

So, if we go and load this page up (we can't go to this part down here--we haven't gotten there yet), you can see,0165

the true literal is...and that literal is a bool data type, as we expected, and its value is true, as expected.0172

At the same time, the false literal is interpreted as a boolean, and it's the false value, just as expected.0178

Now, you can also (as we are going to be commonly doing) assign boolean literals to variables.0188

And then, you can assign a variable that has a boolean value to another variable.0194

For example, here we have three variables we have created.0199

One is called testBool1; we set it to the boolean literal value true.0203

We have testBool2, which we set to the boolean literal value false.0208

And then, we have created one called assignBool, where we have just done an assignment operation,0212

which is saying "Assign the value of testBool1 to assignBool," so it's going to be true.0217

And then, we just use the var_dump function on all of these different variables.0223

And if we go and look at the output, you can see, testBool1 is a boolean data type; it's true.0228

testBool2 is a boolean data type--it is false; and assignBool is a boolean data type of value true.0233

So, comparison operators: what are they?0243

Well, as the name implies, they are used for comparing two different data values.0247

They are binary operators, and because they are binary operators, as we know with binary operators, they operate on two expressions.0252

And as an operator, it takes expressions as input, and it generates expressions as output.0260

The output of a comparison operation is a boolean value, and what it does is compares the values.0266

Depending on the different comparison operators we are going to talk about, if the comparison is valid, it outputs true; if it's not, it outputs false.0273

Now, PHP has several common comparison operators: there is the equal operator, which is two equal signs, not one.0281

The single equal sign, as mentioned down here, is the assignment operator, which you have worked at before.0289

The equal comparison operator, which compares the value of two variables, is not the same.0295

It is two equal signs: and that is sometimes a common problem with new programmers to PHP--getting mixed up with using one equal sign versus two.0300

One equal sign is an assignment operator; two equal signs is the equal comparison operator.0311

I'm going to see what that looks like in code in a minute, and what that is for doing is to compare if the two operands of that operator are equal or not.0317

There is also the not equal operator, which is an exclamation point, followed by an equal sign.0326

There is an optional convention to also use the less than and greater than symbols.0333

It is not as commonly used, and in this course we are going to be using this one exclusively.0339

What the not equal operator does is compares the two operands that it is given.0343

If they are not equal, it outputs true; if they are equal, it outputs false.0348

Then we have the greater than and less than comparison operators, and what those do is:0353

they return true, for example, if the operand on the left is greater than the one on the right--it returns true; if it's not, it returns false.0358

And then, there are two other versions of each of those--the greater than or equal to or less than or equal to,0367

which does the same sort of comparison, but allows the value to be equal, as well.0373

So, you could say "2 is greater than or equal to 2"; the answer would be true, because it's not greater than, but it's equal to 2.0378

And the greater than or equal to operator looks like this, and the less than or equal to operator looks like that.0386

If you remember, back from math, this is how it used to be written--greater than or equal to, and then the less than or equal to is written like this.0394

And so, the equivalents of these are these operators here.0404

Let's take a look at...we have some code here that demonstrates all of the different operators.0410

I have gone through and...all of the different operators we have just mentioned--shown some different examples of how they work.0418

And rather than looking at the code, we will look at what the output of it looks like.0425

Here we see the output of some comparison operations.0433

The equal operation--the way it works is: you have one operand--one value; you have the equal comparison operator; and then you have the other operand.0437

What it does is: it compares those two values; if they are equal, it returns true.0452

It says, in this case, 1 is equal to 1--that is true; 1 is equal to 2--that is not equal, so it returns false.0456

You can do it the same for all the different data types; so for the float--for example, 1.0--is that equal to 1.0? True.0465

But 1.0 is not equal to 2.0.0472

So, as you can see from these comparison operations, they make a comparison, and then they output a boolean value as a result.0475

You can see some string comparisons here.0482

One thing you can note is that the comparison operation for strings is case-sensitive.0485

So, here we have hello; we are comparing it to the other string, hello, and that is going to return true, because they are the same.0490

But down here, we have hello that is in all lowercase, and then we have Hello with the first letter capitalized.0498

And as you can see, that is going to return the value of false; the string has to be exactly the same, character-for-character.0504

You can also compare boolean values; so in this case, we are comparing the boolean literals we have just learned about.0511

Is true equal to true? Yes, so the result of that comparison is true.0517

Is true equal to false? No; the output is false.0521

Now, the not equal operator is just the opposite of the equal operator.0524

If the two values it is comparing are not equal, it returns true; if they are equal, it returns false.0528

So basically, all of the examples that we had up here--in the not equal operator, they have the opposite result.0533

And you can see, if you look down, every result is the opposite one.0540

For example, true is not equal to true--that is false; they are not equal.0543

1.0 is not equal to 1.0--that is false, because they are equal.0547

Now let's move on to the greater than or greater than or equal to comparison operators.0553

We can see how they work: basically, it's an operand, and the operator, and the right operand.0560

And 2 is greater than 1 is true; 2 is greater than 3 is false; 0566

and because this is not a greater than or equal to operator, 2>2 is also going to return false, because it is not greater than 2.0571

Down here, we have done these same examples, but we have used the greater than or equal to operator.0578

So, 2 is greater than or equal to 1 is still going to return true; 2 is greater than or equal to 3 is going to return false.0582

But 2 is greater than or equal to 2 is going to return true, and that is because of the additional constraint of it being equal.0588

And then, the same thing applies down here for the less than or equal to.0597

The same exact operations, but just in reverse--it's a less than or a less than or equal to operation.0601

Now, PHP also has two other comparison operators, known as the identical and not identical operator.0611

All the other comparison operators we had talked about compare the values of the two operands.0620

It compares the value on the left to the value on the right, and if they're the same, it outputs true or false, depending on what the comparison is.0624

The identical ones are similar to the equal and not equal operator, except not only do they compare the values of the two operands,0632

but they also compare their data types.0639

So, not only do the values have to be the same--they have to be, for example the number 1; 0641

for 1 to be equal to 1, they both have to be the same number, but they also need to be the same type.0646

So, a 1 that is represented as an integer and the number 1 that is represented as a float are not going to be the same.0650

Not identical is the opposite of that...0659

Well, first of all, identical is represented by three equal signs; that is the identical comparison operator.0664

The not identical comparison operator is an exclamation point, followed by two equal signs.0669

And basically, what the not identical one does is: it compares the two values and, if they are not identical,0675

meaning if they are not the same value and they are not the same type, it is going to return false.0680

For example, down here we have a variable a, and we are setting it equal to 1, the numeric value 1.0686

We have a float that also is the number 1 (so numerically, they are equal).0693

So, if we come down here to this first comparison, and we use just the regular equal comparison operator from before,0698

that just evaluates the numbers based on their values.0706

Since they both have the same numeric value, 1, this is going to return true.0709

However, if we use the identical operator, which is three equal signs, it is going to return false, because,0715

even though they have the same numeric value, they have different data types.0722

Here, they were both a value of 1 numerically, but one was an integer and one was a float.0728

Let's look at some examples of that, as well.0734

On the same script, we have the identical and non-identical operators down here.0737

As you can see from before, the integer 1, testing whether it's equal to 1.0--it returns true, because they are both numerically 1.0743

The values are both the same.0751

Here, we use the identical operator; it compares 1--is it identical to 1?0753

The answer is true, because they are both integers, and they are both equal to a value of 1.0757

Down here, we compare the integer 1 to the float 1.0, and as we mentioned, that is going to return false0762

because, even though they have the same numeric value, they are of different data types.0769

And not identical works in the opposite way.0774

So, for example, we have the not equal operator--1 is not equal to 1; that is false, because their values are the same.0777

And we could say 1 is not equal to 1.0, and that will return false, because the numeric values are the same, so they are equal, so not equal returns false.0785

However, if we do 1 is not identical to 1.0, it is going to return true, 0794

because in order for that to return false, they have to have the same value and be of the same data type.0799

In this case, they have the same value, but they are not the same data type, so they are not identical; it is going to return true.0809

Now, we are going to talk about the null data type; and null is a special data type--it doesn't fall into the scalar or composite data type categories.0818

And basically, what the null data type is used for, is for variables that have no value.0825

Now, a variable always has to have a data type to be used, whether it's an integer, a float, an array...we just learned about the boolean...0830

But if there is no value assigned to a variable, the absence of a value is considered its own data type.0839

That data type is null, which is the absence of a value.0845

There is one null literal to assign; if you want to assign a value, make a variable equal to null, or of the null data type.0850

You assign it the special key word null; and again, like true and false, this is case-insensitive, how it is interpreted by PHP.0859

And the convention, again, is to use either all uppercase or all lowercase letters.0868

And so, the way you can have a variable be equal to null (meaning it has no data type) is: you can specifically assign it the literal value null.0872

Or, two other options: you can create the variable and not assign a value to it...0882

For example, you could just have a statement that is a followed by a semicolon; assuming we have never declared a before in our script,0888

a is going to have the value of null, because you haven't set a value to it.0898

The other thing is: if we have a variable that has already had a value, and we want to make it null--we want to have it so it has no value--0901

we can use the unset construct, which looks like this.0907

And what you do is: you pass the variable that you want to set to null into it, and then, that variable is now no longer set, and it's equal to null.0912

Now that we have learned about comparison operators, we can make use of the equality operator.0925

A common operation is to compare variables to null; that is like, say, we have a variable num1, 0930

and we want to see whether it is associated with a number yet--if it has been initialized.0937

We can say "num1--is it equal to null?" using the equal to operator.0941

If it is equal to null, that is going to return true, and if it's not, it is going to return false.0951

And so, that is a common comparison we are going to do.0956

Let's take a look at a script that does that.0958

We have a script called null.php, and here we have three different variables.0963

We have a variable called val1, and here we explicitly set it to NULL--the NULL literal--an all-capitalized version, which we are going to use in this course.0971

And that means that val1 is a null data type; it has no value associated with it.0979

The other thing that we can do to get a variable to be a null data type is just declare it, but not initialize it.0986

So, here we have declared val2, a new variable that hasn't been used in the script before.0992

But we didn't assign it a value; therefore, its value is null.0997

The other thing that we can do to give a variable the null data type is to unset it.1000

Here, we have a variable, val3, that had a value (1), and now we want to unset it so it can't be used, and set it equal to null.1007

We pass it to this unset construct, and simply...the way you do this: you write unset, and then,1015

in between parentheses, you put the name of the variable.1019

So, after having done all three of these declarations and this unset, we can compare each of these variables to null,1022

to see if they actually are null, as we expect them to be.1032

So, down here, there are three separate operations; we are starting to use the comparison operator already.1036

We are saying, "Is val1 equal to the null literal?" meaning "is it equal to null?"1042

And because this is a comparison operation, it returns true or false.1048

So, if it is equal to null, it's going to return true; and if it's not equal to null, it's going to return false.1051

Because we just explained that these three ways are how you set a variable to null, we expect all of these to be equal to true.1055

And if we go and load the page, which is going to output these three boolean variables that we have (isNull1, isNull2, and isNull3),1064

we can see that, when we explicitly set something to null, that one equals null.1078

We said, "Is null equal to the result of comparing val1 to null?"--we see that isNull1 is true, because this value is equal to null.1083

Now, we have the val2 variable, which had been declared but not initialized.1094

We tested if that is equal to null, and the output of that is that it is true--it is equal to null.1098

And then, the third way to set something to null is to use the unset function for a variable that has previously been initialized.1105

And so, we had val3 that had the value of 1; now, we unset it, and when we compare val3 to null, we get that the result is true.1111

Really quickly, I just want to mention the coding conventions that we use in this course.1123

For both the boolean literals and the null literal, we are always going to use the all-uppercase versions of these.1128

These are the two boolean ones, and that is what we are going to use for null.1133

That is probably the most common convention out there.1138

Additionally, we had mentioned that the not equal operator has another version, which is this less than, greater than operator.1141

In this course, we are always going to use the exclamation point, equal version of that operator; that is the more common one used.1148

For homework, I just want to have you go over the comparisonOperations.php page 1159

and make sure you understand how all the comparisons work--the greater than or equal to, the greater than,1165

equal, not equal, and so forth, as well as the identical ones, to make sure you understand the subtle difference between 1169

the equal operator and the identical operator, and also between the not equal operator and the not identical operator.1176

That is in comparisonOperators.php, which is one of the scripts we just learned.1183

And also, I'll have you review null.php, the script that we just looked at, and the slide on the null data type,1188

to make sure you understand the concept of null, which is the absence of a value,1194

and to see the three different ways in which a variable can end up with the value null, or with the data type null.1199

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you at the next lesson.1206

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be discussing the topic of type casting, which is a way of converting variables of one data type to another data type.0004

In today's lesson, we are going to talk about a couple of things.0014

We are going to first talk about a term called type juggling, which is something that PHP does,0017

which is a way it automatically converts variables of one particular data type to another.0023

We are going to talk about type casting itself, which is the actual process of doing that.0031

And then, we are going to talk about a couple of different common conversions, like when you cast or convert a variable of one data type to another.0034

Certain rules apply, and certain things occur; and we are going to talk about some common cases0043

for strings, for some arithmetic operations, and for converting things to boolean values.0048

Type juggling--what does that mean? Well, PHP is known as a weakly-typed language.0056

What that means is that, when you declare a variable in PHP, you don't have to give it an explicit type.0061

So, when we do a=1, we are not saying to PHP that a is an integer variable.0066

PHP determines the variable's type from its context; so if we assign it an integer, it is going to be an integer variable.0077

If we assign a variable a floating-point number, PHP knows that b is a floating-point number.0084

This is different from strongly-typed languages, where, for example, in another language, you might...0091

if you want to declare a to hold an integer, you have to preface it with, for example, the int keyword, which says that a is a data type integer.0096

Now, the thing about PHP is: because it's weakly typed, a variable can also change data types.0106

Whereas, in other languages, you might only be able to assign integers to a variable that is declared an integer,0113

in PHP, if you have a=1, this statement will say "a is an integer that is equal to the value 1"; we can, in the very next line,0119

say a=2.5, and we have just implicitly changed the data type of the variable a.0132

PHP now knows that a is a float data type; and it does that on its own.0139

And because, in languages, operations and functions require data of certain types to work (for example, numeric operators require numbers;0144

the string concatenation operator requires strings to be its operands)--because they require that, 0155

PHP does what is known as automatic type conversion.0162

In other languages that aren't weakly-typed, you have to explicitly use...for example, if you are adding integers, 0166

you have to explicitly use two variables that are of the data type integer.0174

In PHP, it does that for you automatically.0179

If you try to add two numbers, and they are not both integers, PHP does an automatic conversion for you.0182

We are going to learn a little bit more about the specifics of numeric conversions that it does.0187

For example, when we add two numbers, it requires them to be numbers.0193

If you provide, in PHP, two variables to an addition operator that are not numbers, 0196

PHP is automatically going to convert them for you to the appropriate type, and then perform the operation.0202

This automatic conversion is known as what the lesson is titled today, type casting.0208

That is converting data from one data type to another.0213

Because this happens automatically in PHP, PHP has certain rules that it follows when it does this.0218

They may not be that obvious, so it is important that you understand the automatic casting rules that PHP uses,0223

so that you can get expected results.0230

Type casting, as mentioned, is the process of changing a variable from one data type to another data type.0235

This can be either done implicitly, as in automatic type conversion, where PHP converts the data type for you, 0241

or you can do it explicitly, where you can explicitly say, "I have a variable that is an integer; I want to make it a float."0250

There are two ways to explicitly cast a variable from one data type to another.0257

You can use parentheses syntax, which we are going to talk about in a second, or the settype function.0262

For example, if we have the variable here int1 that is set equal to the integer literal 1, and we want to make that a float variable,0268

what you can do is: we can create a new variable called float1, and what we do is set it equal to the integer variable name.0277

And then, what we do is: we have parentheses with the word float in between them.0285

What that means is: this parentheses segment right here says, "Take the value of int1, convert it to a float, and then assign it to float1 over here."0291

settype does a similar thing; the way settype works is: it is a function that has two arguments, 0303

which we are going to learn more about when we learn more about functions.0310

But for right now, you can just know that you write settype and then a pair of open and closed parentheses.0312

And then, you pass it two pieces of data: you pass it the variable you want to cast (in this case, we are going to cast the variable num),0318

and then you pass in a string that says what you want to cast it to.0326

So, what this operation is going to do is cast the variable num, which maybe is an integer, to a boolean.0330

It is going to change it from a number data type, like an integer data type, to a boolean data type.0338

Now, one thing to note is that, when you use parentheses casting, as up here, 0343

it doesn't permanently change the data type of the variable that it's casting.0348

So, when this operation here completes (I'll clean this up a little bit)--when this statement right here completes--int1 is still going to be an integer.0353

It's just that its value was converted to a float before it was assigned to float1; but int1 is still an int.0364

If you use the settype function to explicitly cast it, it changes the type of the variable specified.0370

So, this is essentially the same as if we had used parentheses form.0376

Whereas, up here, the variable to the right of the cast in parentheses--its data type doesn't get changed; 0390

down here, because we are assigning it back into the same variable name, its data type does get changed.0400

That is what the settype function does.0405

What are the different casts that you can do in PHP?0409

Well, you can cast between any of the different data types; you can change all of the data types from one to another.0411

Using the parentheses syntax, there are two ways to cast to an integer.0418

You can use int or integer between parentheses, and you just put that before the variable that you want to cast.0421

For float, you can use the word float, double, or real; and those are sort of legacy terms that the floating-point numbers used to be referred to as.0428

But the most typical one you will see will be float.0438

To cast to a string, you just put the word string in parentheses.0440

And just so you know, all of these are unquoted; these aren't previous strings--these are keywords in PHP.0444

So, PHP knows to interpret that as that this is a cast.0450

And then, to cast to boolean, you simply do boolean, or bool.0454

To cast to null, you put the word unset in between parentheses, which is kind of like the unset function we talked about in the lesson on the null data type.0459

The reason it wouldn't normally be null is because we can't use this, because null is another keyword in PHP.0469

As we know, it is the literal value for the null data type; which is why you use unset to cast the variable to null.0479

Something we are not going to really deal with that much, but I'll mention for the sake of completeness, is: 0488

you can also cast things to an array, using the word array, and to an object.0494

And the settype function allows all of these same casts; it just uses a different format.0500

So, if we want to cast to string, for example, you would type the function settype, and then we would put the word string in quotation marks,0503

because this function actually needs a second argument to be a string.0519

And in this case, it's a string set to the value string; but we also could...maybe we want to cast string, and we want to cast it to an integer.0526

So, we could put int in it, as well.0537

Let's take a look at some PHP code that uses these in action.0541

Here are some explicit tasks using the parentheses syntax.0547

Here we have a float variable called float1 that we are assigning the literal 1.25.0550

Then, we are going to create an integer variable; its value is the float1 variable's value, cast to an integer.0556

So, it's going to take 1.25, cast it to an integer, and set it equal to int1.0565

And, as mentioned, parentheses syntax doesn't touch the data type of float1; float1 is still a float data type with value 1.25.0571

However, int1 is going to be of the int data type.0582

Then, we go ahead and do another cast: we cast int1, which is an integer, to a string, using the parentheses syntax with the word string in between them.0585

And then, we convert the string to a boolean, using the boolean cast, when we simply put bool in parentheses.0593

If we look at the output of this script, we can see the parentheses syntax we have.0602

We declared a variable float, because it's 1.25; and then we run the var_dump function on that variable float1.0610

And the var_dump, again, outputs the type and value of a variable--it says it's a float variable that is equal to 1.25.0617

Now, in the other line of code, where we have created an integer variable which is the value of the float variable passed to an integer,0625

we can see that int1 is an integer data type, and its value is 1.0633

So, as you can see, one thing you might notice is that it stripped off the .25, because integers are whole numbers, and they can't have fractional parts.0639

When you cast a floating-point number to an integer, it actually strips off the fractional part.0647

And so, that is something important to notice.0654

Also notice, though, that, because this was a parentheses cast, it doesn't change the type of the variable to the right of it.0656

And so, float1 is still a float variable with value 1.25.0664

Now, we are going to go ahead and have int1, which is equal to the value of 1, and we are going to cast it to a string.0669

And we can see down here that that makes this string1 variable of the string data type.0675

And in this case, the var_dump for strings outputs the length of the string, which is one character.0681

Here, what it has done is just taken the number 1 and converted it to a text string, which is just the text representation of the number 1.0688

There is a difference between the number 1, just flat-out, and then the number 1 in quotation marks.0697

The number 1 in quotation marks is a string, and it is treated as such.0705

The number 1, as an integer or a float value, is something you can do arithmetic operations on.0708

And the string version, you can do string operations, like concatenate and stuff.0716

So, that is where data types do become important, in that you might look at the 1 as being the same thing...0719

There is a 1 here and a 1 up here, but they are not quite the same.0726

Then, finally, we did a boolean cast of the string; and we can see that the boolean one has become a bool data type, and its value is true.0731

And if you notice, the string1 is still a string, and it still has the same value.0741

And so, what happened is: when you cast a string value (we are going to learn more about this in a couple upcoming slides),0746

to a boolean, it has certain rules to decide whether it becomes true or false; and the number 1 ends up being true.0756

And so, there are a lot of different rules when it comes to type casting, and it's somewhat complicated.0765

There are a lot of different things to go over, and so, at the end of the lesson, I'm going to have a link to a page on the PHP website0772

where you can read more about it, because there are many, many different scenarios of how casting from one type to another--what actually happens.0779

As mentioned, parentheses syntax does not change the type of the value operated on.0789

It only changes the data type of the value for the assignment operation.0794

If we go back and look at the code again, there is a section created for explicit casts using the settype function.0801

I have done the same kind of thing we have done up here, with the same variables and the same values.0809

We have a float equal to 1.25 that we have cast to an int; then, we have an int equal to 1 that we have cast to a string.0812

A string, which is the text string 1, or the character string, which is just the text character 1--we are converting that to a bool.0820

What we are going to see when we look at it is that, unlike the parentheses syntax, it changes the type of the variable that is passed to the function.0829

So here, we have a float that equals 1.25; when we pass it to the settype function, and we pass it this string parameter,0841

that says int, which means "cast it to an int," float1 now is actually an integer, and it is an integer value of 1.0848

So, the actual data type of float1 changed.0856

Likewise, for all of the other different conversions...when we convert int1 to a string, 0861

int1 becomes a string data type with a string which is the number 1.0865

And then, down here, if we have a string that is (I don't know why this is unclear, but it is) the number 1 in between double quotation marks,0871

when we cast that variable to a boolean type, string1 becomes a boolean data type that is true.0878

And so, as mentioned, settype permanently changes the type of the variable that you pass to it when it does a cast.0885

So now, I want to talk about a couple of common conversions.0895

There are many different rules, as I mentioned, that happen when converting from one data type to another.0897

We can't go over all of them, but I'm going to talk about a couple of the more common ones.0902

One of the most common conversions is converting things to strings.0906

And actually, we have already been doing this in our code.0909

We haven't explicitly talked about it, but any time you use double-quoted syntax and variable interpolation,0912

where you have a variable within double-quoted strings, PHP is converting the value of this variable to a string data type.0917

For example, if we had a=1, and then we echoed the variable a in between parentheses,0932

what PHP is going to do is: it is going to go; it is going to get the value of the variable a, which is the integer 1;0943

it is going to cast it to the string data type, because echo only knows how to print out strings;0949

and then, after that cast, then it outputs it.0953

So, some of the common conversions that happen to strings are: if you have an integer or a float, when you convert them to a string0956

(which you have seen in some of the code that we have done, like in our store web application, for example,0965

like the calculation of the price), it takes the number, and it just converts it to its text version.0970

So, 14 becomes the string 14; if we have a float value, like 2.5, that just becomes a string, 2.5.0975

That is a pretty intuitive conversion; some of the less intuitive ones are--if we convert the boolean value true to a string, it becomes the value 1.0989

If we convert a boolean value false, it becomes the empty string, which is just a string with no characters in it.1000

And if you convert null to a string, it also becomes the empty string.1008

For example, let's say we had a boolean variable bool1=true, and then we wanted to output that.1013

We did echo "$bool1"; what it is actually going to output is: it is going to take bool1; it is going to see that it is the value true.1031

It is going to convert it to a string, which, as we can see over here, is 1.1044

So, the output of this is going to be just the string 1.1048

Now, one thing to note here is that, in this echo statement, I have enclosed the variable in double quotation marks.1056

And typically, you wouldn't do that; you would just write echo and then the variable name.1063

You would use the double-quoted syntax when you had other things that you were including in this string here.1070

Like you might say "bool is equal to___" and then output the variable's value.1075

But when you use it in this way, as well, without the double-quoted syntax, because echo works on string values,1079

it is going to implicitly cast this bool data type to a string, which, in this case, becomes 1.1087

This is also going to echo out; it is going to echo out the string 1.1092

There are also some numeric conversions that happen; we talked about one earlier.1099

One of the most important ones is when you convert a float to an integer; it rounds down to 0--it just basically strips off the fractional part.1105

So, if you have a number 1.76, and then you were to cast it, let's say, to an int, then its value would now just be 1.1112

That is something important to note.1123

Now, also, the addition, subtraction, multiplication, and division operators--they all require float operands to operate.1125

So, when you have an addition operation or a multiplication operation--any of these--it takes both the operands,1136

and it converts them to floats, and then performs the operation.1142

Now, because, for example, it is going from int to float, the only other type of number that we would have would be an integer.1148

When we convert that to float, it simply becomes the same number; so 1 as an integer would just become 1.0 as a float.1154

That doesn't really cause any problems, whereas going from float to integer, you end up losing information.1164

So anyway, these operations all convert both of their operands to float values, perform the operation, and then return a float value.1171

The only exception to this is when you have two integers that are evenly divisible; then, it actually returns an integer.1183

The other thing to note, as far as automatic arithmetic conversions go, is using the modulus operator.1192

The modulus operator converts both of its operands to integers before it performs its operations.1199

So, if you had something like 7.5 mod 3.0, PHP would convert them both to integers, so this would actually end up being...1205

We know, when you convert a float to an integer, it strips off the fractional part, so it would become 7 mod 3, which is equal to 1.1218

I want to finish up with talking about some boolean conversions and different rules that apply when you convert certain values to a boolean.1230

Basically, as far as booleans go, any value that you cast to the boolean data type is going to be true, except for these cases right here.1240

If you cast the integer 0 to a boolean, it is going to end up being the boolean value false--1251

likewise, for the float value 0, the empty string (which is just a string with no characters), or a string containing just the number 0, and also null.1259

So, if we were to cast boolean null, the value of a would be false.1269

The rule with boolean conversions is: anything except for these values is going to be interpreted as true.1288

For the homework challenge today, I would like you to go and look at this link on the PHP Manual website.1299

Explore some of the links on this page: it's called Type Juggling.1305

It also has a section in it called Type Casting, which is the heart of the material.1308

Just kind of explore around, because there are a lot of different rules that apply when casting from one data type to another.1314

There are a lot of different intricacies when you go from floats to ints, and then especially...we talked about some of the more common ones:1318

converting floats to ints, converting numbers to strings...1324

But then, you can also do things like convert strings to numbers, convert numbers to booleans, and so forth.1329

And there are all sorts of different rules that apply, and so, in order to know exactly 1335

what PHP is going to be doing when you use these operations, you have to refer to the website1339

to find out all of the different things that happen.1344

And the rules aren't too many, but they are somewhat complicated, and so it would be a good idea to go and review them before you start using them.1347

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you at the next lesson.1356

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we will be providing an official introduction into using functions.0004

Specifically, we will be going over what functions are; we will be talking about several different facets of using functions,0012

such as function calls, return values, and function chaining.0019

We are also going to explore a reference on php.net, which is a function reference that provides documentation for all the built-in functions to PHP.0024

And then, part of that is: we are going to go over optional function arguments, which we will learn about as we go through.0034

And then, we are going to cover some common functions in three different groups: string functions, array functions, and then date and time functions.0040

I said the title of this lesson is an official introduction to functions; and the reason I said that is because we have been using functions already.0052

We were first introduced with the phpinfo function that outputs all of the information about a PHP configuration.0061

We have also used other functions, like the var_dump function that outputs the type and values information of a variable.0067

So, we actually have used them before; now, we are just going to officially talk about what a function is.0075

Basically, a function is a group of statements that can be executed on demand.0080

It is essentially a section of code that usually performs a specific task--for example, getting the length of a string.0088

And this is a task you might perform over and over again, so you set it aside in a block of code, and then you name it.0095

And then, what you can do is: you make what is known as a function call, 0102

which is a way to invoke that section of code and perform the function that you need.0107

What happens is: when PHP is processing a script, and it reaches a function call, it stops execution of the current script, 0114

goes to where the function is defined, runs the function code, and then returns back to the original PHP script after performing the function.0123

Now, as mentioned, PHP has a built-in library of functions that provide commonly-needed tasks, 0133

such as working with strings, working with arrays, and working with dates and times--which are all things we are going to learn about in this lesson.0141

There are also many extensions that are built into PHP, such as a MySQL extension for using the database...and so, those are built in, as well.0148

How do function calls look? How do you make a function call?0164

Well, we have used them before with phpinfo and var_dump; essentially, a function call, 0168

which requests the execution of the code defined in the function, is simply the name of the function, and then a pair of opening and closing parentheses.0173

In this case, the time function is a built-in PHP function, and it gets a current timestamp of the date and time right at the moment.0185

That is an example of a function with what is called no arguments.0194

There are also a lot of functions...most functions accept arguments.0198

What arguments are is expressions provided in between the parentheses of a function.0203

It's a way to pass data and information into the function, so that it can work on it.0210

For example, here we have a built-in PHP function called strlen; what this function does is returns the length of a string that you pass in as a function argument.0216

In this case, our function argument is the string abc, and so what happens is: when this line of code right here is run,0227

when PHP gets to the strlen function call, it stops execution, goes out to the strlen function code,0239

uses this value right here that was input as a function argument to the function, and returns the length of that string.0247

That is the particular function...the string length function.0254

In this case, it would return the value of 3.0257

One thing to note is that functions expect their argument values to be of a certain type; in this case, for example, 0260

the string length--obviously, you pass in a string.0267

And one thing to note is that, if you pass a function arguments that aren't of the correct type,0270

the return value (which we will learn about in a minute) of a function is undefined, which is just stating that the way the function will work is unknown.0278

Another thing to mention is that sometimes I've heard function arguments referred to as parameters.0289

We just mentioned the term return values; what that means is: functions, like variables and literals, are expressions.0298

And because we know from our lesson on expressions, function is something that has a value; a function has a value.0308

What a function's value is known as, is its return value--this phrase right here.0315

What it is: when the function executes, it will return a value to the original script where it was called from.0322

For example, if we have this line of code right here--we have a message variable, and we have a string literal,0329

and we are concatenating to it using the concatenation operator we had learned about, the output,0337

or the value of the strlen function with the argument abc...0345

Now, we just learned that strlen is a function that outputs the length of a string that is passed into it as an argument.0351

So, what is going to happen is: when PHP reaches this section of code right here, it is going to go and evaluate the strlen function.0357

strlen is going to give a return value of 3, so that is the value of the function, and it is going to essentially replace it in line.0364

So, instead of having this anymore, you have 3, because 3 is the value of the function, or the return value of the function.0372

Essentially, this line up here would end up with a message that has a string literal: length is 3.0379

One thing that you can do with functions is known as function chaining.0391

Because functions take expressions as their arguments, and a function, as we just learned, is an expression itself--0394

it has a return value--you can use a function call as an argument to another function.0401

For example, PHP has a built-in function called getdate, and it accepts one argument that is a timestamp 0408

(what is known as a UNIX timestamp, which we will get to in a few slides).0418

So, what it does is: it outputs an array of date information.0422

So, what you can do is: you can use the time function, which creates a timestamp, as the argument to the getdate function.0426

What happens, in this case, when this line gets evaluated here: PHP goes to evaluate this function, and then0437

it sees that its argument is a function itself, so it goes out and it finds the time function.0446

It executes the time function, and whatever value that returns--it then passes that value into getdate.0454

And getdate uses that to produce its output.0460

Functions can be chained together as many levels deep as needed.0464

For example, there is also a function called implode that we are going to learn about.0468

You can, for the function implode...what it takes is an array as its second argument, as we will find out.0474

And because getdate returns an array, you can use getdate as its argument.0482

And additionally, we learned that getdate takes a timestamp, and because the time function returns a value that is a timestamp,0487

you can include that as the argument to getdate, and you can include this whole function chain as an argument to the method implode.0495

One nice thing about PHP is that it has a lot of built-in functionality.0505

And at php.net, there is a documentation known as the Function Reference that provides information 0509

about all of the built-in functions provided by PHP.0516

Specifically, one of the things it provides are function prototypes, which are basically descriptions of how to use the function.0521

It describes the arguments, and the types of arguments, the function takes, as well as what values it returns.0527

Additionally, the documentation just has some general information about what the different functions do.0534

It is part of the PHP manual, and you can find it at this address, which we are going to go to in a second.0540

It documents all of the core, built-in PHP functions, as well as the PHP functions provided by common extensions.0546

For example, it is common to interact with the MySQL database using PHP; and so that is a common extension.0553

So, in this Function Reference at php.net, you can find information about the functions provided by the MySQL extension.0561

Let's go take a look at the php.net Function Reference.0570

The way that you would get there is: if we go to the PHP homepage, and then select Documentation at the top of the page,0576

and English, it brings you to the PHP manual, which we have gone to before.0587

And if you scroll down the PHP manual, there is a section called Function Reference.0591

If we click on that, that brings us to the Function Reference for PHP.0596

What it does (let me blow it up a little bit) is: it lists, by category, all of the different functions that are built into PHP or provided by extensions.0601

For example, if you scroll down, you can see all sorts of different functions that are provided.0613

When you look in the text processing category, there is a subcategory called strings, which is an extension--0619

a part of the PHP core--that provides string functions.0629

And so, when we go to the strings Function Reference, you can see, there is a link called string functions.0633

If we click on that, what it does is: it lists all of the different string functions that are available to you as a PHP programmer.0643

If we go down, and we look at a function we had talked about (let's see, where is it?), the string length function,0654

and we click on that, here we can see what we just talked about as a function prototype.0661

What this says is: it gives the name of the function, strlen in this case, and then it defines the arguments that the function accepts.0668

In this case, it accepts a string argument; and in the sections below, it describes what the arguments are meant to be.0676

And so, this identifier right here is used below; for example, the first parameter is called string.0686

So, when you go down and look at the More Documentation, and you look at the parameters list, you can see string.0692

It tells you that this argument is the string being measured for length.0698

Additionally, what you can tell is that this function to the left of the function name is its return value.0703

And so, this shows that this function, strlen, returns an integer.0710

And if you look further down, there is also a section on return values; in this case, it says, "The length of the string parameter, on success, is returned."0714

"And if not, if the string is an empty string, it returns 0."0723

This provides information--it gives a description of what the function does, and then it provides information about how you would call the function.0726

You would know to call it by passing it a string as an argument.0734

And it also provides information about knowing what sort of result you should get from it--what value it will give you.0737

In this case, we know that it's an integer value.0742

One other thing that you can do in PHP is: functions can have optional arguments.0749

For example, you might have a function that can take one argument, or it can take two arguments.0757

Or maybe, sometimes, it can take even three arguments.0764

Functions can be specified so that they have required arguments, and then also any number of optional arguments.0769

Well, the PHP manual's Function Reference that we just looked at has a way of denoting optional arguments to functions,0775

which is important so that, when you go to look at the manual to review different functions that you may want to use,0784

you will understand that they are optional functions.0789

If we go and look at the date function...and one of the nice things about the PHP website is: at the top of the screen, it has a search box.0791

It says "Search for___ in the___" and it has a dropdown box, and you can select (what is selected by default: function list).0800

If you type the name of the function that you are looking for (in this case, we are looking for the function date), and you hit Enter,0807

it will bring you to the function description page for the date function.0814

And here, again, we have a function prototype; it says the function's name is date; it returns a string.0819

And then, here is where it says it accepts as its first parameter (which is a required parameter) a string (and they're calling it format).0825

And then, the way it signifies its second parameter as optional is by including it in square brackets.0833

So, because this first parameter is not enclosed in square brackets, this is a required parameter.0838

However, because the second parameter or argument is included in square brackets, 0846

that lets you know, as a programmer, that you don't have to provide that.0851

But what it also tells you is that, if you do provide the optional parameter--it tells you that it needs to be of the integer data type.0855

Additionally, for optional arguments, they always have default values.0866

So, here you can see that what happens if you don't provide this optional argument when you call this function:0870

it is going to implicitly assign to this second argument the value of the time function.0878

In this case, it is going to say...if you just call date with one argument, you are going to provide a string to it,0885

and then, for the second parameter, it is automatically just going to use the output of the time function.0890

Now, we are going to talk about some commonly-used functions as they relate to strings.0901

Strings, you work with a lot in PHP; we are constantly outputting and changing around HTML tags.0906

And PHP has a wealth of built-in string functions, and this is a list of some of the common ones.0912

We are going to go through some examples using these functions.0921

These first two--as the name implies, they are used to convert a string that you pass into it as an argument to all uppercase or all lowercase.0925

If we go look at a page created for this lesson called stringFunctions.php, we can see (let's blow this up a little more)0939

a code example of using the strtoupper function.0953

Its use: this is my version of the function prototype; it's string to upper, and it takes one parameter as its value, which is a string.0957

So here, we have an example of calling the strtoupper function, and it would use this syntax here.0968

Here, we are passing it the value Ca, which would be an abbreviation for the state of California.0974

And if we were to output the value of this function, it would output CA.0979

And additionally, here we have the strtolower function, which is similar, except that when you pass it a string value,0988

it converts it all to lowercase letters.0994

Now, one thing to note, if we go and look at the source code behind this, is that in double-quoted strings,0998

we can output variables using variable interpolation.1007

However, even though a function is an expression of value, we can't include a function call within double-quoted strings.1012

So, for example, for this first part--for the strtoupper function example--1020

what we have done is called the strtoupper function on this Ca string, and assigned it to a variable.1026

And then, what we have done is: in our output statement, we have included that variable within our double-quoted string.1034

So, we'll echo it out; and that is because you couldn't replace upper with this--that wouldn't work, and PHP wouldn't know how to evaluate that.1042

However, what you can do, if we look at the strtolower example: instead of having this extra step where we create a variable,1057

and then supply the variable to the echo statement, we can use the concatenation operator (which we had learned about).1063

And so, we put the initial part of our output message; we close that string; and then, we call the strtolower function on the string variable,1070

which here is matthewm@educator.com, for example.1083

This function is going to go out and run and return the value, which is a string in lowercase.1087

It is going to add that string by concatenation to this original output string, and then it is going to concatenate at the end a break statement.1093

That is one thing to be aware of: you can't include functions within double-quoted strings, as you can variables.1104

Some of the other functions that PHP provides is called implode, which converts an array to a delimited string; we are going to look at that in a second.1113

There is a string replace function, and what you can do with that function is replace all the occurrences1126

of a certain string within another string with a replacement string.1132

So, for example, you have a string maybe 50 characters long, and it contains the character a five times.1139

You could use the str_replace function to replace the character a with b.1145

We also have the explode function, which is the converse of the implode function; it takes a delimited string, and it deconstructs it into an array.1150

There is the strpos function, and what that does is: you pass it a string and a character sequence that you are interested in finding1161

in that string, and it returns the position of where that character sequence occurs in the string.1168

There is the substr function, which is going to allow you to return a specified portion of a string,1175

and then the strlen function, which we have talked about, which returns the length of a string.1181

Let's go take a look at some of these functions in action.1186

If we look at our stringFunctions.php file again in our web browser, here we can see the use of the implode.1188

The way implode works is: you pass it a delimiter, and you pass it an array.1198

What it does is takes all the values from the array and creates a string, where they are delimited by the delimiter that you pass into it.1202

So, in this example, we have passed to implode the colon delimiter, and we have passed an array containing three different values.1211

It has two strings and an integer, and what this implode function would output is right here.1218

And as you can see, it's a string of all the values in the array, delimited by colons.1226

Now, one thing that we could do is: let's say we change our mind, and we don't want to use a colon as the delimiter in the string.1233

Well, we can use the str_replace function to replace it with a different delimiter.1239

The way that works is: it has three arguments.1244

The first one is the string that you want to replace, which can be one or multiple characters.1248

It has the replacement string that you want to put in its place, and then the third argument is the string that you will be searching to do the replacement in.1252

In this case, the string we want to replace is the colon character, and we want to replace it with a comma.1262

And the string that we are going to perform this replacement operation on is the delimited string that we had up here,1270

which is the array values, separated by colons.1277

Once we get the output of this replace function, it is then going to give us this right here, which is a comma-delimited list of the three values in the array.1283

Now, we are going to demonstrate the explode function, which is, again, the converse of the implode function,1296

which takes a delimited string and deconstructs it into an array.1304

The way explode works is: you pass it two values--you pass it, as a second parameter, the string that you want to extrapolate into its parts.1312

And then, you provide the delimiter that you want to use to know where to divide the string up.1321

In our case, because we have replaced the colons with commas in our string, we are going to explode, using the comma as our delimiter.1329

We are going to pass it the comma-delimited string.1340

What that is going to do, as you can see, to the output, is: it is going to output an array of length 3.1343

What it is going to do is: it is going to extract everything before the first comma into the first value of the array.1351

It is going to extract everything before the second comma into the second value of the array, and so on.1359

Here, you can say we have an array of length 3, and the three values are 1000, Baseball Glove, and 29.99.1365

Now, we also mentioned this strpos function, and what that will do is: it takes as an input a string, and then,1375

you provide an additional search string that you want to find out what position that string is located at, or if it even occurs in the string.1383

Here, we provided the string position function with this value $1099.99.1392

We are saying we want to find the position of the decimal point, and what we get for output is the answer 5.1402

Now, if we look here, the period, or the decimal point, is actually the sixth character in this string.1409

We have 5 before it, and then 1; but the reason it outputs 5 is because the strpos function uses a 0 index.1419

It names the first position of a string as being 0, so the dollar sign is 0, 1 is 1, 0 is position 2, 1428

the first 9 is position 3, the second 9 is position 4, and then the decimal point is position 5.1436

What we can do is: let's say that, now that we know where the decimal point is, we want to extract out the fractional part of the dollar, or the cents part.1444

Well, we can use the substr function; that takes as its argument a string, and then it takes two integers,1454

one being what position the string you would like to start extracting a substring from is in, and from that position,1461

it uses a third parameter, length, to decide how many characters from that position you gave it you would like to extract.1469

In our case, we pass it the same string, which is $1099.99, and where we want to start is: we want the last two digits in the number.1476

And because we know that the decimal point before is at position 5, and we want to start at position 6,1489

we use as our second parameter 5+1--we would use the position of the decimal point at 5, and we add one to it1499

to say "start at position 6, and then give me a substring of length 2, starting at position 6."1507

And so, our output would be 99, because starting at position 6, the next two characters are 99.1514

And then, just quickly, as we had talked about before, the strlen function outputs the length of a string.1523

In this case, for the decimal portion of the number that we just got, if we had saved it in a variable 1529

and then input it to the strlen function, we would get the output of 2, because the string contains 2 characters.1535

Let's go back to those slides...and now, we are going to talk about some different array functions that are commonly used and are built into PHP.1546

The first one is the analog to strlen, but for arrays; it's count, and what that does is returns the number of items or values within an array.1557

Then, there are two search functions, in_array and array_key_exists.1567

What those functions do is return true or false, depending on whether a value passed to those functions exists in that array.1572

In particular, in_array searches...you pass it a value, and it searches all the values in the array to see if the value exists.1580

array_key_exists, on the other hand--whatever you pass it as its value, it searches all of the keys of the array to see if that key exists.1588

Additionally, there are many sort functions, but two ones that we are going to talk about are sort and ksort.1597

What sort does is: it sorts a function based on value; so if all your values were, let's say, integers, in a random order,1606

and you ran the sort function on them, it would resort the array so that the functions 1612

were now in ascending numerical order, which is the default sorting order.1616

One thing to note is that this does remix the array, which can be a problem if you use this function on an associative array.1621

We are going to talk a little bit about that in our example; that is going to be one of the homework challenges--1631

to use the Function Reference at php.net to find a function that will sort an associative array by values, that maintains the indexes.1636

Also, we have the ksort function, which, like sort, sorts the function, but it sorts it based on keys, so it sorts the keys in ascending order.1647

This keeps the key indexes.1658

Let's take a look at a file called arrayFunctions.php, which demonstrates some of these different functions.1662

The count function--it simply takes an array as its one argument.1672

And in this case, we are passing to the count function an array with three integers in it: 10, 8, and 9.1677

And it gives us an output of 3, stating that there are three values or items within the array we passed to it.1684

Now, the in_array function takes, as its second parameter, an array you want to search.1692

And then, as its first parameter, it takes a value you want to search for.1697

So, in this example, we are calling the in_array function; we are saying, 1701

"I want you to look in this array that has the three elements 10, 8, and 9, and tell me if the value 9 is one of those items in the array."1707

And because it is, it, of course, outputs the value true.1716

Now, you can also do this on associative arrays; for associative arrays, we know that this part 1720

to the left of the array assignment operator is the key, and then the part to the right of it is the value.1727

So, when we run in_array on the associative array, it searches all of the values of the array, which are the values to the right of the array assignment operator.1734

So, when we search this array that has three items in it, with each item having the different keys, c, b, and a, and then they have different values,1748

and we are searching if the value Smith exists, this function is going to output true, because, as you can see,1760

the value of the first item in the array, associated with the key c, is Smith.1766

And just to show that this only works on values and not on keys, if we were to run the same function using the same array,1771

but passed it the value c, and said, "Is c in this array?" it is going to return false.1779

So, even though it's a key and it's in the array, it returns false, because in_array only searches the values of an array.1784

Now, on the other side of things, we have the array_key_exists function.1794

What that does is: similarly, it takes an array as input, and then it searches for a particular key (it looks like a type here--this should say key).1800

And then, it returns true or false, whether that key exists.1812

So for example, if we run array_key_exists on a numerically-indexed array that contains the numbers 10, 8, and 9,1816

well, we know from our lesson on arrays that the first item in a numerically-indexed array has index 0; 1823

the second item has index 1; and the third item has index 2; and the index is also known as the key.1830

And so, we are saying, "Does the key 2 exist for this array?" and the output is true, because the value 9 has the index, or key, of 2.1838

So now, we are going to try this on the same associative array before.1849

We are going to ask if it has the string b as one of the keys in the array, 1852

and it is going to return true, because this second key/value pair has b as its key.1858

And again, to demonstrate that this function only searches keys and not values, if we pass the same array,1865

and then ask it to search for the key John, it is going to return no, even though John is in the array,1871

because John, in this array, is a value and not a key.1876

So now, we are going to talk about the sort function; and what that does is: you pass the sort function an array,1882

and it sorts the array by values; it resorts the array in ascending order for values.1889

If we pass it the array with the numbers 10, 8, and 9, in this random order, the output that the sort function would generate,1898

or what it does to the array we pass it, would be: the 0 element would become 8; the second element would become 9; the third element would become 10.1905

You can see, it orders them in ascending order.1915

Now, similarly, if we run this on the associative array, we can see that it sorts by values, and it makes the first value in the sorted array1918

equal to B., because in ascending order, B. is highest up on the list.1932

Additionally, John would come next in alphabetical order, and then Smith.1939

So as we can see, it sorted on the different values in alphabetical order.1944

Now, the thing to notice, that I mentioned on the slide, was that this re-indexes an array.1948

So, in this case, now these a, b, c keys are lost.1953

And as mentioned, one of the homework examples is going to be to research in the Function Reference1957

to find a function that will sort this array right here, but after sorting it by value, it will maintain the key associations.1961

Then, finally, we have the ksort function; and that is a sort by key.1972

And so, it takes one argument, which is an array; so if we pass the ksort function this associative array we have been using all along,1977

it sorts the array by key, so a is higher than b, and b is higher than c.1987

So, the a key is going to be first in the array now; the b key is going to be second; and the c key is going to be third.1993

And we can see that the values that were associated with each key remain with that key.2001

This function is a way to sort by key and keep the key/value associations together.2009

Now, I just want to wrap up by talking about some date and time functions that are available.2020

PHP has a bunch of built-in date and time functions, the first of which that we are going to talk about is the date function, which returns a formatted date.2027

You can optionally pass a timestamp for the current date and time, and then you pass it a format string.2038

And based on this string that you pass to it, it will output or format the string in a particular way.2045

We have the time function, which returns what is known as a UNIX timestamp.2053

We are not going to really get into the details of the UNIX timestamp, but basically, what a UNIX timestamp is, is an integer number2058

that represents the current date and time when the function is run.2065

So, when you run the function time, it returns an integer of time right now, and that integer is known as a UNIX timestamp.2070

Then, we have the getdate function, and what that does is: you pass it a timestamp, and from that timestamp,2081

it can separate into parts the different parts that the timestamp represents.2089

It can separate into hours, minutes, seconds, the day, year, the month, and so forth, and it returns it as an associative array.2093

Also, there is the make, or mktime function, that you can use to build a UNIX timestamp from supplied date values.2102

One thing to note is that date and time functions have a couple of directives within php.ini that they use to configure how they work--2113

in particular, the date.timezone directive; and what you do is: you can go and set that to a particular time zone identifier value,2122

which can be found at this location here, and that will treat all of your date and times as if they were in that time zone.2136

If we go and look at dateFunctions.php, we can see examples of all of these different functions that we just talked about.2146

One thing that you will notice is...before we get into the details of date, I just want to talk about the timezone directive.2160

Basically, what this function does is outputting the current date and time, and it also outputs the time zone.2168

And right now, the time zone output is CEST, which refers to Europe--Berlin, because that is the default value that was set in php.ini in the XAMPP configuration.2174

So, because we are filming on the West Coast for this course, we are going to go ahead and update the php.ini file.2187

And what you can do is: it's quite a long file, but if you search far down in the page, there will be a date section,2196

if I can find it; there it is; and as you can see, it has the date.timezone directive, and it is set by default, in XAMPP, as Europe--Berlin.2212

What we are going to do is: we are going to set it to West Coast time--so we are going to give it the value america/los_angeles.2230

And the reason we use america/los_angeles is because that is one of the allowed time zone identifiers, or one of the identifiers that it recognizes.2240

The way that you can do that is by going to the link that we had in our slide.2250

For example, if we go to this link right here, it will tell you all of the different time zones that are available.2253

We have gone ahead, and we have updated our default time zone.2261

Because it is a change to php.ini, we need to reboot or restart Apache, so that the change will take effect.2264

And if we restart it and go back and look at our date function that output the abbreviated time zone identifier for Europe-Berlin,2275

and we refresh the page, we can see that it changed to PDT, which is the Pacific time zone.2283

Now, where you can find these is on the link that we had before, which can be found by...2294

if you look up the date and time extension in the PHP manual, you can find the list of supported time zones, 2306

which...it would be easier for you to just cut and paste the link, if you had it before.2312

And you can see that it has listed different continents and areas in the world, and you can click on an area, such as America,2316

and see the different values that you are allowed to use.2323

If you look down here, you can see that, for West Coast time (let's see, where is it? My eyes aren't serving me well--oh, it was off the screen)...2326

You can see that they have one for America, Los Angeles, and you can see that it uses an underscore.2352

But for example, if you were on the East Coast, you could use the america/new_york to use East Coast time.2357

So, now that we have set the time zone for this installation of PHP, let's talk about the different functions we had mentioned.2369

Basically, the date function returns a formatted date string.2378

It can take two parameters; and actually, if we go and look at the date function in the PHP manual,2382

and again, we are going to use the search box up here--that is easier, we can see that it takes a string as its first parameter.2390

And optionally, it takes a UNIX timestamp as its second parameter.2397

And the parameter defaults to time, which is the current unit timestamp, if not provided.2402

If we run this function date, which we are here, with just one parameter, it is going to format our date based on the current time.2408

And as you can see, it explains that in the description: "Returns a string formatted according to the given format string,2416

using the given integer timestamp, or the current time, if no timestamp is given," which is what happened in our case.2422

Now, this parameter called format, which is a string--you can see down here, 2430

it provides a lengthy description of all of the different values that you can include in this format string.2434

There are all sorts of different things that you can do: you can use it to output days, months, years, seconds...2440

You can do it with leading zeros or without; and there are just different ways to extract and format different pieces of a timestamp.2447

So, in our example, we have gone ahead and used the formatting string right here.2457

And on your own, you can go ahead and look and research, and see how this format string translates into the output that we get here2464

by looking at this format parameter description; it shows all of the different...basically, they are just like formatting characters...2473

that you can use to output certain parts of the date.2482

In this case, this formatting string formats the current time, because we didn't provide a second parameter.2485

And it says "output the day of the month, the month, the year, a comma, and then output the hour, minutes, seconds, using AM or PM."2491

So, we are not using military time; and then, "also output an abbreviated form of the time zone identifier."2502

Now, as mentioned, the time function, which is our next function we are going to talk about, returns a UNIX timestamp2509

for the current date and time, which...when we run this script right now, and we refresh the page, is going to change.2515

And as mentioned before, a UNIX timestamp is an integer that computers know how to work with,2522

and can decode into the date and time that it represents.2528

That is how the time function works.2534

The getdate function takes as an input a timestamp; and in this case, we could run the getdate function with the time function as its parameter.2536

And so, time is going to generate, as its return value, the current timestamp.2549

And so, getdate knows how to take that timestamp and extract it into different parts, and it outputs an array.2553

And as you can see, it's an associative array that contains all sorts of different keys--seconds, minutes, hours, month, year, and so forth,2561

and extracts the date information and the timestamp.2569

You can see that it knows that, when this getdate function is called, the hour was 4; the minutes were 9; and the seconds were 46 seconds.2572

And then, you can also see that it was June 24, 2011.2586

Now, what you could do is: now that you have these date values, you can use the mktime function to build up a UNIX timestamp.2596

There are different functions for going back and forth between UNIX timestamps.2602

The mktime function works by passing in...it has a specific order of arguments it takes.2606

It first takes hours, then minutes, then seconds, the day and the month and the year, and it will generate a UNIX timestamp based on that.2611

If we go ahead and pass it, the values that we got in this array up here, dateArray, which was received from the current date and time,2620

and we pass it those values--you can see that it generates a UNIX timestamp.2632

And if we notice, because we use the same values that were generated by the getdate function,2636

we should generate the same UNIX timestamp as was used in the getdate function.2644

And as we can see, part of the getdate associative array that it returns--the last value in the array, 2651

with the key of 0, is the UNIX timestamp that it used to dissect all of the different parts of.2658

And as we can see, because we use the same parts down here in mktime, these two values match up.2664

That ends the course material; I just want to talk about a couple different homework challenges that we have for you,2673

that are going to give you some experience working with functions and calling functions in more detail,2679

and using some of the functions that we went over.2683

In this homework example, which you will be able to look over, you can see that we are just going to have you convert string to uppercase and lowercase.2687

And then, practice chaining functions--for example, if you pass an uppercase string to the lowercase function, it would return it lowercase.2694

And then, you pass that value to the uppercase function; it returns it to uppercase.2708

So, by chaining those two functions together, you essentially get the original value.2712

That is one of the things that we are going to have you do.2716

And then, I will have you create an array that just contains five integers, 2717

using float functions to create a string where the integers are separated by colons.2724

And then, like we did in the course, I will have you replace the colon delimiter with commas.2730

And then, we are going to have you use the strpos function in a little bit different way than we used it in the course,2735

to find the position of the first comma in our now-comma-delimited string.2740

And then, we are going to use the substr function to remove the first integer in our comma-delimited string.2745

So, we are going to have to remove the integer, as well as the comma that precedes it.2754

So, just remember, when you do that, that these string position and substring functions consider the first character to be 0 and not 1.2761

That will give you a little experience with that; and it is kind of challenging, and a little tricky, at first, 2770

getting used to using these strpos and substr functions, so it should be a good exercise.2773

Then, I just want to have you run the explode function on our now-shortened list of integers.2779

And then, because explode generates an array, we will have you use the count function to verify that the array length is now 4, instead of 5.2784

For the second challenge, I am going to have you work with some of the array functions we learned about.2796

I am going to have you create an associative array of the 12 months in the year, in ascending order, 2800

so that it starts with January and ends with December, where the key is a string value of the number of the month.2805

And then, the value is the month name spelled out.2814

Make sure that you declare them in ascending order.2819

And then, I want you to look at the php.net Function Reference (and this is to give you practice in learning to use the reference)2821

to find a function that will sort the array in reverse order.2828

Right now, it is sorted from January to December, and I want it to sort the other way around.2834

One way to quickly find the array functions that are available--a little hint I'm going to give you is that, if you type ksort,2840

which we know sorts an array by keys--if you type that in the Function Reference box at the top of the page,2846

if we go and do that quickly...instead of having to search the Function Manual for all of the different array functions,2851

we can see that, because ksort is an array function, that on the left-hand side, it lists all of the other array functions that are available.2861

I want you to go through and find one of these functions that will reverse sort an array.2867

Have it sort by the keys, which are numeric.2877

And then, you verify that by printing out the array to make sure that it's in reverse order.2883

Then, resort the array in ascending order back to its original version, using the ksort function that we had learned about.2888

And verify that that is done with print_r, and then sort the array by value.2896

What that is going to do is: it is going to sort the array according to the value, which is the month name.2902

However, I don't want you to use the sort array; I want you to research in the Function Reference again2912

to find a function that will sort an associative array by value, but keep the key associations,2918

because if we run the sort function on it, what it is going to do is: it is going to sort the months according to value,2924

which would make April the first one, but it's going to give it an index of 0.2930

In order to keep the index (for April, which is the fourth month) of 4, you need to find a new function that will maintain that index.2934

After you find that function and apply it, use print_r to verify the sort by value.2941

And, if it is done correctly, April should be the first month, with a key of 4, and September should be the last month, with a key of 9.2948

Then, I'm just going to have you practice with the array_key_exists and in_array functions 2959

to verify that January is not a key in array, but a value, and that it is a value in array.2964

If you did a search on array_key_exists, it should come up false; if you did a search on in_array using the value January, it should come up true.2972

One thing to note is that these functions return boolean values, and if you try to echo a boolean value,2981

as we learned from our type casting course, the echo statement implicitly casts a boolean value to its string equivalent.2987

And for true, we know that it gets converted to 1, and for false, that gets converted to the empty string.2995

Just keep that in mind when you try to echo the results of these arrays, so that you will understand that it is not going to output true or false.3000

Finally, for our last homework challenge, I am going to have you work with the date and time functions.3010

The first thing I would like you to do is update the date.timezone directive in your php.ini file to your current time zone.3014

And remember to restart Apache after you make the change, because any configuration changes require a restart of the web server.3024

What I would like you to do is use the date function to output the current time in 24-hour format, which would just be the hour and the minutes.3033

And include an abbreviated time zone identifier, so that you can know that the change you made up here3044

to the time zone in the php.ini file works.3049

And what you will need to do to do this is: you will need to research the date function in the Function Reference3054

to learn how to set that first format parameter you pass to date to get it to output the things you want.3062

So, look back at the Function Reference; if you go to the date function, you will have to search this section down here,3067

that talks about the format parameters, to learn about the different format characters you use in order to output a date in the format you would like.3077

Then, I would like you to use the getdate and time functions and chain them together, so that getdate3088

will output an array of the current date and time information.3093

And then, using that getdate array like we did in class, I want you to use the date in that array with the mktime function3097

to generate a UNIX timestamp that matches the timestamp that was used when you called the getdate function...3106

as mentioned, you are going to use the time function.3114

That is going to sort of replicate what we did in the course; and if things work out right, as we have shown,3117

the timestamp that you generate from mktime should match the last element in the getdate array, which has a key value of 0.3123

Those two should match up.3132

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.3135

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be talking about what are known as constants.0004

Particularly, in this lecture, we are going to be going over the difference between constants and variables.0011

We are going to talk about how to name a constant--talk about constant identifiers.0017

We are going to talk about the different ways you can declare constants within your PHP code.0023

And then, we are going to go over some coding conventions that we are going to use for this course when it comes to constants.0027

We are also going to talk about the _SERVER superglobal variable, which is a superglobal variable,0033

like the _get variable that we have used to process form data.0040

We are including that description in this lecture, because it's something that is often used when defining constants in web application configuration files.0046

What is a constant? Well, as the name implies, it's a value that doesn't change.0057

In PHP, specifically, it's an identifier that you can assign a value to.0062

However, unlike a variable, once it has been assigned a value, that value can't change during the execution of the script.0067

This is something that is enforced by the PHP Interpreter; so, if you define or declare a constant, and set it equal to one value,0073

and try to do it again later in your script, you are going to get a warning, and then also the redefinition is not going to work.0080

One other difference between constants and variables is that variables can be used to hold any PHP data type--0087

arrays, the scalar data types, special data types like null.0094

However, constants can only be assigned scalar data types, which, as we know, are integer, float, string, and boolean.0098

It can only be one of those four data types.0105

Additionally, as mentioned, constants are often used in what you would call config files0111

for defining constant values that you use in many places throughout your web application.0118

I say "things that never change," because basically...they change, but they are not going to change during the execution of your web application.0125

Examples might be the sales tax rate, which isn't going to change very often.0134

And maybe you will have an email form on your website, and you always want it to email to a default administrator's email address.0138

That is something you could define as a constant.0146

Now, the way constant identifiers work is similar to variable identifiers.0150

The one big difference is that they don't begin with a dollar sign; other than that, all of the same rules apply.0155

They have to start with an underscore, letter, and then after that, they can be any combination of letters, underscores, and numbers.0162

Here are a couple of examples of four different constants that we have declared.0168

For example, we have declared a different constant for each of the different scalar data types, 0174

which are the only types, again, that you can use to assign to a constant identifier.0179

We created one, DAYS_IN_A_WEEK=7, set the sales tax rate to 10%...we have a string, SERVER_NAME, that we set to educator.com.0184

And then, we might have a boolean constant in our configuration file that says, "Are we going to require a password?"0195

And in this case, we set it to true.0202

One thing to note, in particular, is that, unlike variables and variable identifiers, you can't use a constant within a double-quoted string.0206

So, variables--you can make use of variable interpolation; but that does not work for constants.0215

If you output a constant name within a string, it is just simply going to output the name of the constant.0220

We know what constants are and the rules for their identifiers in PHP.0229

Now, let's talk about how we actually declare constants within our code.0234

PHP provides two different methods; the first method is through the use of a function called the define function,0239

and the second is using an assignment statement with the const keyword.0246

And this bullet right here shows the two different syntaxes in action.0252

Here, we are using the define function to define a constant called PI, and we are setting it equal to the float value 3.14.0257

Now, if we wanted to do the same thing, using a constant assignment method, we have a variable name called the assignment operator,0267

and the value we are assigning to it, and then we precede all this with the const keyword.0277

That says that we are declaring a constant pi and setting it equal to 3.14; this value cannot be changed.0282

One major difference between the two forms is that, with the define function, a constant can be defined as the output of an expression.0290

For example, we could define a constant HOME, and let's say we know that the protocol is always going to be HTPP,0299

but we are going to use a variable to set the server name of this home page, and that could be a variable.0309

So, using the define function, we can use an expression in the value portion of the function.0317

And I should mention, actually, that the first argument to the define function is the name of the constant that you want, enclosed in quotes.0323

And then, the value that you want to assign to the constant is the second argument.0333

In this case, we are assigning it a value that is a string, that is the concatenation of this string literal http:/ and the value of the variable serverName.0338

Now, you can't do this with the const assignment version; if we tried to do it down here in the same way, 0353

it would generate a parse error, because using the const assignment method, you can only assign static values.0360

So, we would have to hard-code it as http...0367

That makes the define function, in some ways, a lot more useful; and it is mostly what we are going to be using in this course.0379

Let's take a look at a file called constants.php.0387

Well, before we do that, let's take a look at the actual code that shows you how this defining constants works in real PHP code.0392

So here, we have a define statement that defines, as before, the constant PI, giving it the name PI in capital letters.0402

We are assigning it the value 3.14; and then here, we have an echo statement that echoes the pi value.0410

And remember, as mentioned, you can't include constants within double-quoted strings.0416

So, in order to output it as part of another string, we use the concatenation operator.0420

And then, here we have a constant declaration that uses the const assignment method.0426

So, we are declaring the variable pi, and in this case, we are making it a little more precise, 0436

and we're setting it to the value 3.14159, as opposed to just 3.14, and then echoing it.0441

However, as we know, constants cannot be redefined; so when you try to run this page right here, 0449

when you try to make this second declaration, you are going to get an error generated.0456

Additionally, the constant PI is not going to get updated; so when we echo PI down here, 0461

it is not going to echo the second value that we tried to set it to, but the first one.0466

So, if we go and look at this page, constants.php, we can see, it output 3.14 twice, because PI wasn't reassigned.0471

We also get a notice stating that we had already defined PI within the file.0480

Let me go ahead and...one thing that we could do, if we wanted to make this legal and output a different value for PI--0488

we could create a constant with a different name, called PI2, which would eliminate the error with redefining a constant.0499

And then, we should be able to echo the second value; and let me go through and do this...0506

We don't get the error, and we see that we have the output value of PI2.0511

But that kind of defeats the purpose of what we are doing; I was just doing that to show you how you could change that,0516

so that the error doesn't occur; but typically, you are not going to be doing this.0522

Down here in this other section that I had commented out, I'm going to talk about how you can use expressions within the define function, as we mentioned.0527

For example, we're defining a variable called server, and we're setting it to the value www.educator.com.0536

And then, I'm going to define a constant called HOME_HTTP, which is going to be an HTTP link to that server.0543

And as the value of HOME_HTTP, I'm going to assign it the value of this expression, 0552

which is the concatenation of the http:// string literal and the value of the server variable.0558

And then, in this next line, I am just going to output that variable.0567

Now, if we try to do that same thing down here in a const assignment statement, we are going to get an error,0571

because, as we had mentioned on the slide, constant assignment statements using this method can only have static values.0579

They can't be expressions, which in this case, would be the concatenation of the server variable with FTP.0590

So, for example, if we wanted to create a different constant, HOME_FTP, we couldn't use this type of definition; we would have to replace it.0597

So, if we go ahead and view this page again now, with the section uncommented, we can see that we get a parse error,0606

unexpected . (which is a concatenation operator) on line 43.0614

We go back and look at line 43; we see that this section of code, we thought, would cause an error,0619

because this is not legal syntax; so the way we could replace that would be to just hard-code the link in.0624

And again, this is something you probably wouldn't do; you would usually use the define function, because0635

it gives you this additional flexibility; but to demonstrate this, and to show both of these constants' output,0642

we can make that change, and we won't get the error, and it should output all the information.0649

Here are the two PI values from before, and then we can see the values of the two different constants, HOME_HTTP and HOME_FTP.0654

So now, I just want to talk about some coding conventions that we are going to use in this course for constants.0669

As you have probably noticed, all of our constants were declared using uppercase letters, and spaces between words were replaced with underscores.0674

This is the convention we are going to be using, and it is pretty much the convention that all PHP developers use.0685

It signifies that, any time you see an identifier that is in all capital letters, you know that it is a constant.0691

So, it is what we are going to use in this course, and it is what is used out there in the real world.0697

Additionally, there are those two methods we mentioned for defining constants.0703

We are pretty much going to use only the define function for defining our constants, as opposed to the const assignment statement.0707

The reason for that is: it gives us the added flexibility of using expressions to set the value of the constant.0714

As before, as we talked about in the coding conventions for variables, your constant identifiers should be given meaningful names,0722

so that they describe what their purpose is.0731

Instead of calling something just LINK, you might call it HOME_PAGE, which tells you that the link is to your home page.0734

So now, I want to talk about the _SERVER superglobal.0745

And basically, to mention it again--we haven't talked too much about superglobals, and we're going to get to that later in the course.0749

But a superglobal is a variable that is pre-defined by PHP, and it is made available to you everywhere in your script, and it is automatically populated by PHP.0755

The one superglobal we have used before is the _get superglobal, which is used to access, as we know, GET data that is input to a form.0766

The _SERVER superglobal provides information about the current web server configuration,0778

and also provides a lot of information, like the web server's document root and any HTTP header information for the currently-running script.0784

And it's an associative array, like GET, and one of the more common keys that we are going to use to access this array is DOCUMENT_ROOT,0796

and that provides the full path in the local file system to the web server's document root.0806

And this is useful, because in configuration files, we can use that value to define where include directories are,0812

so that when we include files, we can create an include directory constant, and it will make use of this.0819

And then, that way, when we include a file, it will know which directory to look in.0827

Let's take a look at a file called serverSuperglobal.php.0833

The beginning of this file--what it does is: it outputs the phpinfo.0841

What that is going to do is: that shows all of the information in the _SERVER superglobal, so we can see what it looks like.0850

And then, I have also just added an anchor and a link to the bottom, so that we can quickly get to the _SERVER information,0856

because on phpinfo, it's listed at the bottom.0866

So, if we go and we view this page, and we see phpinfo generated, and click Scroll to Bottom,0868

at the bottom down here, you can see, it has information about the _SERVER variable.0876

It provides all sorts of different information; there is information from HTTP headers about the user agent...all sorts of information.0882

It gives information about the page that was used to refer you to this script page.0891

And in particular, what we are looking for is the $_SERVER ['DOCUMENT_ROOT'].0898

What that says is: that is giving us the document root of the web server that is serving this page.0903

And in this case, it's C:/Users/educator1/xampp/htdocs, which is as we expect.0909

We learned in our lesson on setting up a development environment that the htdocs directory in the XAMPP folder in our User directory0916

is the document root for the default XAMPP configuration.0927

So now, if we go back to this page in the code editor, and uncomment a section we have below,0932

you can see that what I have done is defined a constant called INCLUDE_DIR, which is to represent the include directory.0941

And we set the value equal to the $_SERVER ['DOCUMENT_ROOT'] value, which, as we know, is the htdocs directory.0950

And then, what I have done is concatenated to that a string that directs you to the path of the include directory for, for example, lecture_19.0963

If we had include files in lecture_19, we would put them in an includes directory.0975

So, any time you would want to include a file--for example, 0980

we are in this lecture_19 web application; we want to include a file called header.html--0989

we can use this constant in the file header.html, and PHP will be able to use the constant that uses the $_SERVER ['DOCUMENT_ROOT']0994

variable to resolve this link, and it will know where to find header.html.1008

Let me erase this.1012

So, now that we have defined this constant, I have gone ahead and echoed it.1017

And if we reload the script, it should show up at the bottom of the page.1022

And if we look down here at the very bottom of the page, we can see, it says INCLUDE_DIR, and then it lists the include directory,1031

which is this part right here, which is the document root, which is from the $_SERVER ['DOCUMENT_ROOT'] value.1037

And then, we have appended to it the path to our current include directory.1045

And we can use that, for example, in a configuration file for our web application, to prepend all include files.1050

For today's homework challenge, I just want to give you a little practice with defining constants.1061

We are going to have you use the define function, which is the method we are going to use most in this course.1065

And basically, I want to get you to have some experience with also using expressions to set the value of the constant.1072

So, I'm going to have you define a constant called ADMIN_EMAIL, using the define function.1079

And set its value to a valid email address, and then output its value.1083

That will give you practice defining a constant, and it will also give you practice echoing out a constant,1089

because you will learn that you can't include it in double quotes, as you can with variables.1096

Then, I am going to have you just delete the constant altogether and create two new constants, one called USER and one called DOMAIN_NAME.1102

I am going to have you define the USER constant to be the value that was to the left of the @ sign in your admin email address,1111

and the DOMAIN_NAME constant to be the value to the right of the @ sign in your domain address.1117

Then, I'm going to have you redefine the ADMIN_EMAIL constant, and I want you to use the USER and DOMAIN_NAME constants1123

we just created together to create the same admin email address that was created here in step 1.1133

That is just going to, again, give you a little practice with learning how to use expressions.1141

In this case, the expression is a concatenation operation when setting the value of a constant,1146

and you should be able to output the admin email in this updated script, and it should be the same value as in step 1.1151

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1159

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be going over some Web fundamentals and be discussing how PHP and the Web work.0005

We are going to start by talking about what is known as the client-server model, which is a model for distributed computing on the Internet.0013

We are going to talk about the http protocol, which is used when browsing Web pages.0019

We are going to talk about something you may be a little familiar with already, which is URL's, or Uniform Resource Locators.0025

And we are going to discuss how these different things work together to serve web pages from the Web server to a client.0032

Additionally, we are going to talk about the differences between static and dynamic web pages,0038

go over what server-side scripting is, and then talk about how server-side scripting is used to serve dynamic web pages.0043

First, the client-server model is basically a distributed computing model that describes how information is exchanged on the Web, or over a network.0055

It describes communication between two different parties--one known as a client and one known as a server.0064

Basically, a client is what is known as a resource or service requester.0070

A client makes a request to a server to obtain a resource or to have a particular service performed.0074

On the other side of things, a server is a resource or service provider0080

that either provides a requested resource to a client or performs a service requested by the client.0086

One thing to note is that the terms "client" and "server" both can kind of have several meanings.0094

"Client" can be used to refer both to an actual person using a Web client, browsing to a website,0098

and it can refer to client software, such as a Web browser.0106

And it can actually be used to refer to a client computer (which is maybe a computer where a Web browser is running).0109

On the other hand, "server" can be used to refer to the actual machine where a Web server is running,0115

or it can be used to refer to the software that is running, such as the Apache Web server.0122

The way you distinguish between what is meant by "client" or "server" is typically denoted by the context it's used in.0128

We know that the Web uses a client-server model for accessing web pages.0137

The way it does so is: it uses a set of rules or protocols.0144

In computing, protocols are basically a set of rules that denote how computers communicate with each other over a network.0148

There are a number of different protocols out there.0158

The one that is used on the Web, to browse to a web page0160

(which you may have heard of, and you might recognize from URL's that you have entered into the address bar of your browser),0163

is http--or it's formally known as the Hypertext Transfer Protocol.0169

What that protocol is: it defines how Web servers and Web browsers interact to be able to serve and view web pages.0175

Whenever you type an address in your Web browser (such as this), you will notice that there is the http 4-letter mnemonic at the beginning of the link.0184

What that is basically doing, is specifying to your Web browser that you want to request a particular web page,0195

and you want to use the http protocol to do it.0203

It is standard protocol used on the Web to access web pages.0206

So, you don't actually even...when you type an address into your Web browser, you could just type in educator.com.0210

You will actually see that your browser goes ahead and inserts this http part here at the beginning,0217

because that is the method used to access websites.0222

How does one decide to tell the Web browser what resource it wants to view, what web page it wants to view, and how to view it?0229

The way it does that is through a URL, which is this right here, which we had seen on the previous page.0238

Basically, a URL describes the location of a particular resource on the Internet that you want to view--for example, a web page.0243

And then, it also describes the method of retrieving it.0251

URL's have a specific form: this is a simplified form--there are additional parts that can be added to it.0254

Basically, it contains a scheme which describes the means of retrieving a particular resource.0261

It contains a host name, which is basically the name, or the IP address, of the server that has the content you are trying to retrieve.0267

It can optionally have--well, it actually always has in the background--a port specified,0276

which says on what port you want to connect to the particular server.0281

That "port" is a networking term that is used, that describes how...0286

Basically, computers communicate with each other, and they do so using ports,0291

which are basically numbered assets on the computer (for example, Port 80, Port 100).0294

The last part of the URL is the path; and basically, what that is, is the path to the resource you are trying to find0302

on the server that you are communicating with.0310

If we are accessing web pages, URL's typically have the form shown here.0315

For the scheme, it has, as we saw on the last slide, the http specified.0319

That specifies that you should use the http protocol to load a particular resource on the Web.0324

In this case, the resource is a file called index.html.0333

And then, index.html is located in php directory on the server educator.com.0338

The way that you connect to that server at educator.com is using port 80.0346

Now, port 80 is the default used for communicating with Web servers, and it is typically left out of URL's.0352

And actually, pretty much any time you browse anything on the Web, you never see it.0357

But behind the scenes, it is implicitly being used.0361

That is how your Web browser communicates with the Web server to be able to use http to download a web page to your browser.0363

How does all this work together with the client-server model, the http protocol, and using URL's?0376

Well, let's say, for example, we have this URL here that specifies that we want to use the http protocol0382

to, again, load or view the file index.html located in the php directory of the educator.com server.0388

And again, implicitly, it is going to use port 80 to connect.0399

How does that happen?0402

Well, the first thing you do is: when you type this address into your Web browser, your Web browser initiates what is known as an http request.0403

What it does is: it sends that request over the Internet to the educator.com server.0418

The educator.com server has what is known as an http server--or, more commonly, a Web server--that is listening on port 80 for any http requests.0425

And actually, the most common Web server that is used (or http server) is the Apache Web server.0436

And that is actually what we are going to be using in this course.0442

When you send out, from your Web browser, an http request to educator.com,0444

the (for example) Apache Web server will receive that request, and it will dissect the URL and discover that0449

you want to receive the index.html file loaded in the php directory.0457

Well, the Apache Web server knows how to map these URL's to specific places on a hard drive.0463

So, it goes to the hard drive and loads the index.html file.0468

The file is loaded up by the http server, and then it sends the file back to the requesting client, or requesting Web browser, 0473

using what is known as an http response.0482

This, basically, is the cycle that happens every time you browse to a web page.0490

An http request is issued to a remote server (typically), and then the server responds 0496

by looking up the requested resource on a hard drive and then sending it back by an http method and an http response.0502

The example that we just went over is typically what is used for serving what is known as a static web page.0512

A static web page is one whose content is basically not altered, nor is any task performed, when a web client requests the page.0517

So, basically, a web client doesn't perform any actions or provide any input to the page; it is just asked for and returned.0526

A dynamic web page, on the other hand, can respond and does respond to a web client's action or input.0536

For example, a web client or a web user might submit HTML form information, 0544

like we saw in the introductory lecture about our web store application, where our users submit their shipping information.0551

A dynamic web page can take that input and then perform some action or generate HTML content based on that.0560

For example, in the case of our web store application, it could generate an output that says, 0567

"This is the address you provided where we are going to ship things to."0575

Or, it can even perform tasks, like accessing a database or even processing a credit card transaction.0578

PHP is a server-side scripting language that is used for the creation of these dynamic web pages and web applications.0586

We have mentioned a little bit, in the introductory lecture and now, about server-side scripting.0595

Basically, what server-side scripting is, is what PHP is: it's a programming language that is executed on the server whenever a user requests a resource.0600

For example, when a web client requests a PHP page from the web server (for example, at educator.com),0611

when that page is requested, basically, executable code is run that can be used to perform some actions0619

or to generate some dynamic HTML content that gets sent back to the user.0626

Typically, for a server-side scripting language, the code is always executed on the server.0632

And then it is output, typically, in the form of an HTML; it is returned seamlessly to the web client.0637

From the web client's point of view, all they see is them sending a request for a particular PHP page to a web server.0642

And then, they receive HTML output in response.0649

It is basically the ability to execute code on each page request 0654

that allows PHP to take your web pages and web applications from the static to the dynamic.0659

Additionally, most server-side scripting languages, including PHP, allow executable code (or the server-side scripting code)0667

to be intermingled with HTML markup.0674

For example, if you look at a static HTML page, it just contains regular HTML content.0679

And if we look at the source, we can see, it just contains some simple HTML tags.0690

And that it is all it contains--HTML code; and that is a static web page.0696

However, if we look at a page called dynamic.php, for example, and we load that up, this is an example of a dynamic web page0700

that executes server-side scripting code when it is being processed, or when it is requested.0709

In this example, this web page actually just prints out the current day and time, which is obviously going to change every time the page is requested.0716

If we refresh the page, you can see that the time has actually changed.0723

Now, if we actually go and look at the source code for this particular page,0728

we can see that, rather than just having HTML tags, there actually is a section here0738

(and we are going to learn more about this as the course goes on) where you actually have PHP code.0744

This is how you designate PHP code; and you have it intermingled with HTML.0749

Everything up here is just standard HTML, as we know about.0755

And then, this section of code right here, which is the PHP code, is what actually...0759

Basically, what it does in this case is just echo or output the current date.0763

Every time we view this page--we request this page from our web browser--this page is basically interpreted by PHP.0768

Any HTML is passed back to you, and then any PHP code is run, and the output generated by that is passed back to the user, as well.0777

Let's sort of take a look at the same diagram we had before, but now we're going to use it to talk about serving dynamic web pages.0789

For example, let's say we have a new URL that is requesting a PHP page.0796

It is requesting index.php, and the PHP directory is educator.com.0802

What is going to happen is similar to before.0807

The web client, or the web browser, is going to issue an http request to the web server located at educator.com.0810

That request is just going to say, "I want the contents of the index.php file."0821

Well, when Apache receives that, it knows (it is configured to know) that PHP files are not just simply to be returned to the user.0828

For example, Apache wouldn't want to return this file as is to the user.0836

This content right here, this PHP code, is sort of meaningless to the user.0841

What the user wants is that code executed, and its output.0847

So instead, what happens is: when Apache receives a request for a PHP file, 0851

it basically invokes what is known as the PHP Interpreter (and you will hear me refer to that as the PHP Interpreter, the PHP Parser, just PHP in general).0856

What the PHP Interpreter does is: it loads the PHP file from the hard drive,0865

goes through, and directly passes on any HTML it finds in the page,0870

but then also goes ahead and executes any PHP code and then passes on any output generated by that HTML code to the client.0875

PHP...after loading the file from the hard drive, it executes any PHP code.0883

It generates an HTML output file, which it passes back to Apache.0887

And then Apache, through the same method as before, sends it back by an http response.0892

So again, from the client's point of view, basically, the same scenario is happening.0901

It is simply requesting a file, and the web server is returning an HTML file.0905

However, the difference is: on the server side, there is an extra step in here, which is where PHP comes in.0912

It's a server-side scripting language, and what it does is: it executes code that can be used to dynamically generate HTML, for example.0918

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.0927

Hello, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to continue working on our web application, 0004

incorporating some of the information that we learned in our last few lectures on functions and constants.0007

We are going to quickly just talk about some of the things from the last web application version, which is 5.1.0015

And then, we are going to go through three new revisions of the web application.0022

In version 6.0, we are going to be adding a web application configuration file, which is going to include0027

a lot of different constants, which is going to make managing the application easier.0036

In version 6.1, we are going to make use of the constants in order to move our image directory up one level from the directory tree,0042

which is going to make it easier in developing future versions of the application, as you will see.0050

And then, in the third version, 6.2, we are going to be making use of constants and functions to output the date and time0055

that an order was created, as well as doing some sales tax calculations.0067

If we go and look at version 5.1, this is the store as we know it: it has a View Cart function 0075

where you can select different quantities, go ahead and check out, and so forth.0084

And when you complete your order and enter in your shipping information, it will say your order was completed.0093

What we are going to do is create a configuration file that is going to make managing all these different pages within here easier.0099

In version 6.0, we are going to create a configuration file called config.php.0106

We are going to store it in the version_6.0 in the includes directory; we are going to create a new file called config.php, and that is where it's stored.0112

And in this file, we are going to do a couple of things: we are mainly going to be defining a bunch of useful constants0121

that we can use in all of the web page, because what is going to happen is: we are going to include this configuration file0127

in all of our web pages, and then we are also going to move the catalog.php include that was in all of the pages,0134

and move it here into this one config file, because this is already being included in all the files, so we can locate all of the includes in one spot.0142

The couple of different constants that we are going to define: the first one we are going to define is a version number.0154

And it is just a string, and what that is used for is: we are going to be creating a constant called IMAGE_DIR,0159

which is going to be the location of the image directory for our web application.0167

We are going to build this IMAGE_DIR constant up from what is called the root URI, which is the base URI, or URL, of our web application.0173

As we know from working with it previously (let me go back to Home), we can see that, for example, for version 5.1,0185

the URI after the host name is intro2php/web_app, and then the version number.0196

That is the root URI for that version of the web application.0203

What we are going to do here is: we are going to create a ROOT_URI constant, and we are going to define it as we do here,0208

except that, for each configuration file, or each version as we update, we are going to update the version number.0215

And that is going to update the root URI, because every root URI has a different URL, because they are stored in a different version folder.0221

Then, we are going to create this IMAGE_DIR constant, which is the root URI.0231

And as we know from what we have done in our previous web application, 0235

the images are all stored in a folder called Images in the root directory of the web application.0239

That is what the IMAGE_DIR constant is going to do.0245

Additionally, we are also going to be creating a constant that has a path to the include directory, where we store all of our include files.0248

And in our web application, we store all of the include files in a folder called includes in the base folder of the application directory.0258

What we do is: we create a constant called DOC_ROOT, which makes use of the $_SERVER ['DOCUMENT_ROOT'] variable,0267

which gives you the document root of the entire web server that the script is running on.0276

We are going to append to that the root URI that we created up here.0282

It is going to add to document root the path to the folder of the current version of the web application.0287

And then, we are going to create an INCLUDE_DIR constant that is going to append to this document root,0300

which (the document root) is going to be version-sensitive, because, as up here, we defined...the root URI depends on the version number.0307

And then, what we are going to do is...we have created the document root, and the INCLUDE_DIR is just going to be 0319

that document root for this particular version of the web app, which is just going to be an absolute file length.0323

And we are going to add to it the file path includes/, and that is going to say 0330

that the include directory is at our web application's document root in the includes directory.0337

Then, we are going to define two constants called HTML_HEADER and HTML_FOOTER.0344

What they are going to do is: instead of having to explicitly, in each of our files, 0349

have an include statement that says include/header.phtml, for example, we are going to create that all in one constant.0356

And then, we are going to use that constant in all of our different pages.0364

And what that is going to allow us to do is: let's say we decide to change the name of header.phtml that we want to use for a header file;0367

well, the way we currently have it, we would have to go through every page and update that header.phtml include statement.0375

By creating a constant called HTML_HEADER, which is the path to the include directory, and then the name0382

that we want to use for our HTML header, and by setting that to this constant HTML_HEADER, we can use the HTML_HEADER constant0390

in the include statements in all of our files.0398

So, if we ever need to change what we want to use as our header include file, all we do is update it once in this configuration script,0400

by updating this constant, and all of the different pages will receive the updates.0408

Additionally, at the bottom here, we just have include the catalog, which all of the pages have included normally.0414

But we put it all in this one config file; and catalog.php is located in our include directory.0421

So, if we look previously, for example, at store.php, as mentioned, you can see that we have an include file 0429

that has hard-coded into it include/header.phtml.0437

And in every one of the web pages in our previous version of the web, an application has this hard-coded in there.0442

So, if header.phtml changed, you would have to update all of the changes.0448

Now, what we have done in store.php is: at the beginning of each page, we include the new include file config.php0453

that we just created, that defines all of these constants.0461

And now, our include statement changes to just include, followed by the HTML_HEADER constant.0464

So now, any time we update this HTML_HEADER constant, if the header file changes,0470

what we are going to do is: we update all of the include statements in all of our files to use this constant,0478

so that change will get propagated to all of the different files.0482

And also, if you look at the bottom, you can see that we have replaced the include/footer.html with the HTML_FOOTER constant.0486

The other thing that we have done is: because we created the IMAGE_DIR constant, anywhere we have an image...0497

an image tag in the source...for example, in header.phtml is where the image tag for the logo is placed...0507

what we can do is: in the image tag source attribute, we can just specify to output the image directory, or the IMAGE_DIR,0517

which is the image directory for this particular web app version, and then just specify the image name.0529

What that does is: like with using the HTML_HEADER constant, it allows us to change the location of our image directory.0536

We only need to update it in one spot: we update it in our config.php file.0545

And then, because all of the different files that are going to access images are going to use this IMAGE_DIR constant,0550

by making the change in our config file, all of the pages will get updated accordingly.0556

And so, you can see, we have done that here in header.phtml.0561

In item.php, we output the item's image, and so, you can see, we have used the IMAGE_DIR constant here, as well.0565

And then, in viewCart.php, where we output the list of all the items in the store, it outputs a small version of the image.0576

And you can see that you use the IMAGE_DIR constant here.0583

Now, what that does is: if we pull up the older version of item.php, for example, from version 5.1, our last version,0586

we can see that, in our image tag, the images folder was hard-coded into there.0601

Now, that has been replaced with this IMAGE_DIR constant, so that we can update and change the image directory folder, if we choose.0607

Now, that is also going to change how the links appear in our source coding for HTML.0617

So, if we go and look at index...for example, this is version 5.1; if we view the source of this page, 0622

we can see that (let's get this up) the source for our image is this hard-coded string, images/educator.png.0630

Well, in our new version in app 6.0, we go to store.php, and we view the source; we can see that the image source0641

has now been updated to this absolute URL, which is specified by IMAGE_DIR.0653

And so, this is output everywhere the IMAGE_DIR constant is used.0659

So now, the URL becomes the full path to the image directory for the version 6.0 web app.0663

And we are basically saying "load educator.png from this image directory."0670

So, this page right here--this slide--shows all of the changes that we had talked about.0686

We created a config file, config.php, that contains a bunch of application-wide constants that we can use in all of our different files.0691

We have done this; we have updated all of our files to use the HTML_HEADER and HTML_FOOTER constants.0699

So, if we need to change the header or footer file, we can do it in one location.0705

And then, we have updated all of our places where we have used image tags to use the IMAGE_DIR constant0710

to find where the images are located.0716

In our next version, version 6.0, we are going to take advantage of this IMAGE_DIR constant.0720

We are going to show how it's beneficial, in that we are going to change the location of the image directory.0726

Now that we have included the IMAGE_DIR constant as the path for all of our image tags, by updating that once in our configuration file,0731

it will update it for all of the different pages that include images.0741

So, if we move the image directory, which is what we are going to do in this particular version of the web application,0744

just by updating the config file, all of the pages will be able to find those images.0750

And what that is going to do is: right now, every time we create a new web application, 0755

we are copying the images directory over from one version to the next.0760

for example, in version 5.1, we have all of our files in the folder, and then we have an images directory that contains all of the images.0764

Well, in version 6.0, we have that same image directory with all of those images, and so we are copying them over and over.0772

What we can do is: we copy this directory and move it up one level 0779

outside of the version directory, and just create an images file here.0786

Now, we can reference this directory in all future versions of our web application, and we don't have to copy it into each version folder.0790

Now, this is one that saves disk space, but the other thing that it does is: 0798

it is also showing us the power of being able to use constants to make these changes.0804

So, if we go to our web app (let's close down some of these pages), and we go to version 6.1,0810

first of all, you will notice that the image directory is no longer here--we moved it up one level.0826

If we look at our includes directory, and we look at catalog.php...I'm sorry, not catalog.php; if we look at config.php,0832

which is our updated config file, you can see that we have updated the IMAGE_DIR constant.0840

So now, instead of being intro2phpwebappversionxxx/images, it's just intro2phpwebapp/images.0845

That will be the same for all future versions of our web application.0854

So, if we go and look at the version 6.0 version of the pages, and we view the source, for example,0860

we can see that the source has been updated so that it uses this new image directory.0873

And if we look at, for example, the source code for the header.phtml page, we can see that, as before,0879

we have included this IMAGE_DIR constant to specify the image directory.0894

And because we updated it in our config file, and the config file is included in all of our pages,0900

this header file will always know where to be able to find the different images.0905

Those are the changes for our version 6.1.0915

The final version we are going to talk about today is moving on to version 6.2.0919

What we are going to do is: we are going to take advantage of what we have learned about constants, 0923

and also what we have learned about functions, particularly date functions, to add a little bit of improvement to our web application.0927

First of all, we are going to include a sales tax calculation for the user's shopping cart when they go to check out.0935

And as part of doing that, we are going to introduce the function called round, 0942

which you can look up in the PHP Function Reference, which you now know how to use.0947

And we are going to use that to round out our total to two decimal places, because sometimes,0952

when you do math...like we are going to be calculating based on sales tax...you can get some really long decimal numbers.0956

This is going to round it down to two values, which is what dollars are typically shown in.0964

In order to do this, we are going to be adding a constant sales tax rate.0970

That is going to allow us to set the sales tax rate we want to use for all of our calculations in the whole store, and put it in one place.0974

We are also going to be creating a constant called ORDER_DATE_FORMAT.0981

And what that is going to do is: we are going to be adding to our thankYou page a timestamp0984

that says "Thank you for your order; it was completed at this date and time."0991

And we are going to be using the date function for that; and as we learned, for using the date function, 0995

we know that the first argument that it takes is a string that specifies the format of how you want the date output.0999

We are going to make that format a constant; we are going to set ORDER_DATE_FORMAT to a string1006

that is equal to the format that we want to use.1013

So, for example, let's say we have the format that just shows the month, the day, and the time that the order was purchased.1016

Well, maybe, in the future, we want to update it so that it includes the year, as well.1024

We can go to our config.php file and update ORDER_DATE_FORMAT, so that the string is this new format that includes the year.1027

And then, that change is made.1035

And in this particular version of the web app, we are only using that order date in one spot,1036

so we could technically just hard-code it in that one spot in thankYou.php.1042

But, if, let's say, we want to use this format in other parts of our web page--maybe we want to output the order creation1048

date and time in other web pages--by creating this constant in the config file, we can then use that formatting in many different spots,1056

and only have to update it in one spot, if we decide to change it.1065

As mentioned, we are going to output on the thankYou page the order creation date and time.1069

We are also going to output what the sales tax rate was that was used to calculate the total.1075

And then, the other thing we are going to do is: we are going to make use of the strtoupper function that we learned about1079

so that the state abbreviation the user enters in the checkout form is always going to be capitalized,1085

because sometimes they might, for example, for California, type ca in lowercase.1090

And to properly format it, we are going to capitalize it to capital CA.1094

Let's go and take a look at some of the code for version 6.2.1100

First, let's look at the config file; and you can see in the config file, one thing we did is: we have updated the version number,1108

so that all of our include URL's will refer to the right version directory.1117

I've also added a section here of miscellaneous application-wide constants.1127

Here is where we define order date format, and this is a string with date formatting constants in it 1131

that you can learn about on the date function's web page at the Function Reference at php.net.1142

Also, we have defined a sales tax rate constant; in this case, we are defining it to .1, which is a 10% sales tax.1149

So now, if we go and look at checkout.php...1158

Actually, before we do that, let's go to version 6.2.1166

We'll go to the store; we are going to view the cart; and let's place an order for one of each item; and we go to check out.1171

As you can see, the total has changed from the way it was last time--last time it just outputted the subtotal of all the items.1189

Here, it says, "Your total was 709.48" rounded to two decimal places, and it says "with sales tax."1196

So, we have added to checkout.php sales tax, to our calculation for the total.1202

So, if we go and look back at the new checkout.php, we can see what we have from the other version, version (I guess it would have been) 6.1.1208

And what we have done is: we have updated the variable that used to be called currentTotal to currentSubtotal,1224

because that is often what a total is called before you add sales tax to it.1230

And then, we have updated all of the three operations that add the price and quantity of each item to the subtotal.1234

Basically, we have multiplied the price of each item by the quantity selected and added it up.1245

These are the same operations as before, except they are adding it to the value currentSubtotal.1252

Then, what we are doing here that is new is: we are creating a new variable called currentTotal.1256

which was in the last one, but now it's going to have a different purpose here, because it's going to include the current subtotal, plus any sales tax.1261

The way that we calculate that is: we add to the current subtotal the current subtotal times sales tax rate, which is our constant we defined.1268

So, if we want to ever change the sales tax rate to, let's say, 9.75%, we can update that in our configuration file,1277

and it will get updated here, and this calculation will change.1286

Then, you can see that we have gone ahead and used this new function that we talked about, called round.1292

It takes a float number as its first parameter, and then the number of decimal places you want rounded to is the second parameter.1297

We are going to round this total to two decimal places, because that is what dollar amounts are represented in.1304

And then simply, as before, we are going to output the current total, and then just have a mention that it says "with sales tax."1310

Now, if we go back and proceed with the checkout, notice, I'm going to use lowercase letters here for this date...1320

Scroll down a little bit, and then go to Complete Order, and you will see a couple of things.1343

You can see "your order was completed on___," and we have added the order completion time1348

that shows the date, the time, and the time zone.1353

And we also output, as before, the final total, but we mention that it included sales tax at a rate of 10%.1358

And also, down here, you can see that the user had entered (in this case, I had entered) a lowercase state abbreviation,1364

but to properly output that (we capitalize it), we use the strtoupper function.1370

If we go and look at the thankYou.php page, we can see a couple of changes that were made.1377

First, in the section at the top that outputs information about the order total, you can see that we have used the date function,1390

which by default, if you only specify one parameter, outputs the current date and time 1399

(that would be the date and time this order was created).1403

And we are going to format that date according to the ORDER_DATE_FORMAT constant, which we have defined and declared in our config.php file.1406

And so, if we ever wanted to change it, we could go change it in that one spot, and it would propagate here, as well.1415

The other thing that we have done is: we have output a little message that says, 1421

"with the final total of" and then we output the order total, "including" and then we do a calculation that outputs the sales tax rate,1427

which is basically...to do it in a percent, we multiply the sales tax rate times 100; and in this case, it's going to output to 10%.1435

The other change we had made was down here in the table that outputs all of the address information.1443

We can see that we have used the strtoupper function to capitalize any state abbreviation that was provided by the user.1451

One thing you will notice is that we have used the concatenation operator here, and that is because of what we had talked about before with functions.1461

Functions can't be included within double-quoted strings, as you can variables; 1467

and so, we have to use that to concatenate this value to the city and ZIP code value.1472

And so, this is what our final page looks like; and to give an example of the flexibility this provides,1481

let's say we go back to our config file, and let's say we don't want to output the time zone anymore.1487

So, for example, t is the timezone in the date function format; so if we delete that, and we save it, and we go back to here,1495

right now, we have PDT, which is an abbreviation for Pacific Standard Time, and we update the page.1505

We can see that it has eliminated the time zone identifier.1514

And so, that shows you how...let's say we had used this date formatting in a couple different spots on our website;1518

we just went ahead and updated it in one spot.1522

So, for today's homework challenge, I just want you to, as usual, go through and make sure you can identify and understand 1527

the changes that we made in progressing from version 5.1 to version 6.2.1532

In particular, I want you to consider how the changes we made have increased the flexibility and maintainability1537

of the web application, by using constants in a common config file.1546

We have seen how now, for example, with the include statements for our headers,1550

if we ever want to change the header file that we are going to include, we only need to change it in one spot, as opposed to every page.1555

That increases the ease that we can maintain our web applications, because we don't have to update each page individually.1560

Additionally, these constants provide some flexibility, because now we showed how we could move the image directory1568

to whatever directory we wanted to, and by using a constant to define that, we update the new image directory in one spot,1574

and all of the different pages are now able to find the images.1580

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1583

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be talking about what are known as conditional control structures--in particular, the if and else statements.0004

And it is a very exciting lecture, because for the first time, we are going to be able to make some decisions within our code,0011

based on user inputs and user actions.0016

So, we are going to be able to evaluate certain sections of code, based on things that happen from the user.0020

In particular, we are going to first talk about what is known as statement groups.0027

This is, as the name implies, grouping a bunch of statements together, and they get treated or evaluated as one.0031

We are going to talk about, obviously, the topic of the lesson, conditional control structures, 0038

and in particular the two control structures known as the if statement and the else statement.0043

We are also going to cover a language construct called isset, and then we are going to go over coding conventions as they apply to if and else statements.0048

What is a statement group? Well, essentially, as the name implies, a statement group is a bunch of statements0059

that are grouped together and sort of treated as one.0063

When you evaluate a statement group, you evaluate all of the statements within that group.0066

So, for example, in PHP, the way you denote a statement group is: let's say these two statements...you want them0071

to be executed as a group; you surround them by opening and closing curly braces.0077

What that does is: if this statement group right here is to get executed, that means that both of these echo statements will be executed.0085

So, both hello and world will be echoed out to your output.0092

Now, conditional control structures--what they provide is the ability to execute statement groups on a conditional basis.0099

And what they do is: they test a condition, and if the condition is met, then a particular statement group is executed.0105

For example, PHP provides a number of different control structures.0117

There is the if, the if/else statement (both of those we are going to be talking about today).0121

There is also the if/else/if control structure and the switch control structure, which we are going to be talking about in a couple upcoming lessons.0128

And then, these control structures down here are conditional control structures that allow you to loop over a statement group0138

and repeat it multiple times, based on certain test conditions.0145

And we will be getting those, as well, later on in the course.0149

The if control structure, commonly known as an if statement, is the most widely-used initial control structure.0153

And it is called an if statement (although technically, it is not a statement, as far as PHP goes, but that is the common vernacular0162

for referring to it)...basically, what the if statement does is: it tests the condition, which is a boolean expression.0168

And if the expression evaluates to true, then it executes a statement group associated with the if statement.0175

For example, this is the syntax that the if statement has; and what it has is the if keyword, 0181

and then a test condition immediately following that in parentheses.0187

And if the test condition equals true, then this statement group, 0192

which is all the statements enclosed in these opening and closing curly braces, will get executed.0199

If the condition is false, then they don't get executed at all.0204

One thing to note, also, is that (it's another terminology thing) one refers to executing statements within an if statement...0209

it is called being inside the if statement if this condition is true, and you are executing statements within the if statement's statement group.0219

That is just a terminology thing.0228

One other thing to note about if statements is that, if a statement group associated with an if statement0231

has only one statement in it (in other words, it's a statement group consisting of one statement), you don't 0239

actually have to include the curly braces around it, and the single statement can just be output as is.0244

Let's go and take a look at an example of the if statement in action.0251

Here we have a script called if.php, and it is going to run through a couple of examples of using the if statement.0258

Let's make it a little bit bigger.0268

In this first one, we used literal values as the test condition, and we say "if true, then go ahead and execute the statement group."0271

As we just learned, if the if statement's test condition is true, then the statement group gets executed.0281

Because true is always true, this statement right here will always be executed.0288

Now, if we try the same thing, but we put false as the test condition--false is always going to equal false, which is not true,0293

which means that this statement block in here is never going to get executed.0299

As another example of slightly different using of an expression, we could say, "If 0 is less than 1," and that is a boolean expression--0303

it's a comparison operation; 0 is always going to be less than 1, so this test condition will always evaluate to true.0311

And because of that, this echo statement within the if's statement group will always be executed.0318

Now, one other thing to point out is that these examples up here use literal values, or static values, within the test condition.0327

But more often than not, you are going to be using variables and combinations of variables--0335

in particular, variables using comparison operations--as part of the if condition.0340

In this case, we have a variable called boolean expression, just shortened to expr; we set it equal to true.0347

And then, if we run the if statement with the variable boolExpr as the test condition, what is going to happen is:0355

PHP is going to replace boolExpr with its value, which in this case is equal to true.0363

Because it's equal to true, this statement here is going to get executed.0368

As another example of things a little more complex, we could declare a variable called 1 and set it equal to the integer 1.0372

And then, we could put a comparison operation as the test condition (which is a boolean expression).0381

And we say "if 1, or the value of the variable 1, is equal to the value of 3-2--if that is true, then execute this statement here."0385

And because 3-2 is always equal to 1, this statement will get executed.0395

And down here, you can just see the results of these five different if statements that we had.0399

In the top one, because this was true, 'I will get executed' was printed out.0405

However, because this test condition was false, 'I will not get executed' does not get printed out.0409

And if we look down here, we see that is exactly what happened: 'I will get executed' was printed out, but the other one wasn't.0415

Because 0 < 1 is a true test condition, this is going to be echoed; and we can see that 0 is less than 1.0421

And then, for the final two if statements, because boolExpr in the first one equals true, and 1 is equal to 3-2,0429

both of their echo statements that are part of the if statement would get output.0438

One other control structure that we are going to introduce is known as an else statement.0448

And like the if statement, it is not actually technically a statement in PHP, but that is how it is commonly referred to.0451

It is a conditional control structure that gets associated with an if statement.0457

The way it works is that, if you have an if statement, and the if statement's test condition evaluates to false,0461

and there is an else control structure that follows the if control structure,0467

then whatever statements are inside the else statement's group get executed.0472

And so, for example, the if/else combination has this following syntax, where you have your if statement, 0479

as we had just described--it tests a condition.0487

If the condition is true, it evaluates this statement group; and then, it would proceed to the next line in the code.0491

However, if condition equals false, because there is an else control structure associated with it, then whatever statements0499

are in the else control structure statement group get executed.0510

So, every time this is false, these statements down here will get executed.0514

And as with the if statement, if an else statement group only contains one particular statement,0519

the curly braces around it can be omitted; they are optional.0525

Let's take a look at an example of the if/else control structure in action.0531

Here we have two simple if/else combinations.0540

In the first one, we have an if statement that says "if this condition is true, then we are going to echo this statement here."0544

"And if it is false, this statement gets echoed."0552

Because true (the literal value true) is always true, this statement will always get executed.0554

The else statement group will not be; and then, any code that would be next down the line would get executed after this statement was echoed.0560

Now, we switch things around, and we put the value false as the test condition, because if the test condition is going to equal false,0567

then the if statement group will not get executed.0575

However, there is an else statement group appended to the end of it, so the else statement group will get executed.0578

So here, it will say, 'Now I will get executed.'0584

And if we look at the output of these two if/else control structures, we can see 'I will get executed' was output from the first one,0586

and 'Now I will get executed' was output from the second one.0595

One other thing I want to talk about is something known as the isset construct.0602

This is something that is useful for particularly processing GET data to see if data was passed to the script that you needed.0608

For example, if you are expecting a name/value pair to a script by a GET, where the name is, for example, action,0616

and action is set equal to something like checkout, the isset construct can be used to see if action was passed into the script,0625

by checking to see if that key exists in the GET array.0638

And the way isset works (I'll get this out of the way here) is: it checks two things.0646

One it checks is if the variable that you pass to it has been previously declared, and also it checks that the value is not null.0655

The way it works is: it accepts a variable as its argument, and it returns a boolean value, true or false.0663

For example, if we declare a variable here, a, and we set it equal to 1, and then we run the isset construct on the variable a,0670

temp is going to be set to true; and the reason for that is because a has been both declared, and its value is not equal to null.0679

Now, if we went down here and we changed the value of a, so that it's equal to null,0687

and we run the isset construct on a again, temp is going to be equal to false.0692

And that is because, even though a was declared, its value was null.0698

And then, finally, if we run isset on a variable b that has not been declared (let's assume this is all one script),0702

because b has not been previously declared in this script, isset is going to return false.0710

Let's take a look at what that looks like, again, in action.0717

We have a script called isset.php, and what it does is: because isset returns a boolean value, we can use it within an if test condition.0722

So, this is saying if the variable name was passed to the script by a GET (which means that the _GET array would contain0732

a key/value pair with the key name), if that is set, then we are going to echo these statements here.0746

It says a name was provided by GET, and it is going to output the name.0753

On the other hand, if it wasn't provided, then it is going to use the else statement to output and say the name was not provided by GET.0757

And if you look up here at the top of our script, we can see, we just have isset.php with no GET query string appended to it.0765

So, because there is no name as part of a GET query, isset on checking this variable name is going to return false;0772

it is going to echo "'name' was NOT provided via GET."0786

Now, if we were to go up here and add name (let's say I put my first name in here, Matthew), into the script,0790

now isset is going to return true, because the GET variable name exists.0798

And so, it is going to evaluate the if statement group; so it's going to say, "'name' WAS provided via GET" "The 'name' provided was 'Matthew.'"0803

And one other thing to do, just as a refresher on going over how URL's are encoded--if we remember, spaces in URL's0812

are encoded with a + sign, so if I want to output my first and last name here, I can do Matthew+Machaj.0820

And if I do that, you can see that Matthew Machaj was output.0828

And that, again, is just sort of a review of URL encoding.0830

And the reason that the isset is useful, like I said, is for checking GET parameters, because if you try to access0835

a GET value that was not provided to the script, you will get a warning.0841

And also, if you try to use GET values that weren't passed in, your script is not going to work as executed.0847

For example, we look at the code of isset, and if I were to go in there, and after the else statement, let's say0854

I go ahead and try to echo (move this over a little bit) a GET value, or a GET variable that doesn't exist.0864

Let's call it lastName, and if I try to echo that, because it is not passed into the script, 0882

if we go back and use the same query string as before, we are going to get a warning.0889

And if we look down here and refresh it, it's going to say, notice: undefined index lastName,0894

which says that the key lastName doesn't exist in the GET array, and that is because we didn't provide it.0899

That is one of the main uses of the isset construct--to be able to check if GET data were provided.0905

Now, I want to talk about coding conventions as they apply to if statements and else statements.0914

Basically, the examples we have seen are formatted the way that we are going to be formatting them in class.0921

Namely, first, there will always be a space between the if keyword and the opening parentheses of the test condition.0927

And additionally, after the closing parentheses of the test condition, there will be a space, followed by the opening curly brace.0933

So, the curly brace for an if statement is always going to be on the same line as the if keyword and the if condition, and it is going to be one space after.0940

Similarly, for an else statement, the opening curly brace for an else statement group is going to be on the same line as the else keyword.0948

It is going to be separated by a space.0958

Additionally, any statements within an if/else statement group are going to be indented one level deeper than the if keyword.0962

When we go back, and we look at our example here--in this isset example, we can see that all the statements 0970

within the if statement group and the else statement group are one indent deeper than the if or else keywords.0976

The other thing to note, as you can see in the script, is that the closing brace for an if or else statement group0987

will always be on its own line, and it will be indented the same level as the if or else keyword.0993

And as far as the else statement goes, the else keyword will be on a new line, following its corresponding if statement's closing brace.1002

So, for example, if we look back here, we can see the closing brace for this else's corresponding if statement is right here.1012

So, else is on the following line, as opposed to having else up here, which sometimes you see in different people's coding style.1018

But for this course, we are going to be doing it like this.1026

And then, finally, even though statement blocks, if they contain one statement, don't have to have curly braces surrounding them,1029

as we had mentioned, we are always going to surround our statement groups for if and else statements with curly braces,1035

even if there is only one statement.1042

So now, I just want to talk about the homework challenge for this lesson.1047

I want you to create a script that contains a single if/else control structure.1050

And what it is going to do is: it is going to test, using the isset function, if the variable _GET ID is set.1055

It checks if the GET parameter ID was supplied.1066

If it was--if that is true that it was supplied--you should output the ID passed in.1069

And if it is not true, you should output an error message stating that you need to provide an ID to the script.1077

And what that is going to do is: you should be able to make use of an if/else statement in order to do that,1087

similar to what we had done in the isset.php example in here.1091

One thing I want to say is that I strongly encourage you to not cut and paste code from the lesson examples--1095

that you should practice typing these if/else statements on your own.1102

And the reason for that is: there are often a lot of mistakes involved with if/else statements and control structures in general,1105

where you leave out a parentheses or a curly brace, and so the only way to really get practice with that,1111

and to learn where the mistakes are made and how to correct them, is to get in there and type it on your own.1116

And also, I just want to mention that you should follow (when you write your sample script or homework script) 1122

the coding conventions we just outlined for the if/else statements.1129

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1133

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be covering the topic of error handling in PHP.0005

Specifically, we are going to talk about how PHP handles errors by classifying them according to different levels, and how it reports them.0011

We're going to talk about error reporting function, which is a way of managing how errors are reported in PHP.0019

We are going to talk about a number of different configuration directives within php.ini that affect how errors are handled.0026

And we are also going to introduce a new operator, known as the error control operator, that relates to error handling in PHP.0033

PHP classifies errors according to different levels of severity.0043

And then, what you can do is set the level of severity that you want to be made aware of for a certain error.0048

So, you might want to be made aware of any severe errors, or maybe you want to be made aware of errors and warnings.0055

PHP allows you to set that level, and it also allows you to set how you want to be made aware of it.0062

For example, you could have it output to your browser, or you could have it output into a log file.0070

And the way that you set the level that you want to see in PHP is using this directive called error_reporting.0075

It's a configuration directive in php.ini, and what it does is: it globally sets the error level that you want reported 0083

for all of your scripts running in a particular PHP configuration.0090

And what you do is: you set that configuration directive to a number of different error level constants, which can be found at this link here.0095

If we go and look at this page (it's part of the PHP website), you can see that there are different constants,0116

which are...for example, the first one defined is E_ERROR; the constants are integer values.0118

And then, PHP has different constants for different levels of errors.0123

For example, E_ERRORS is for fatal runtime errors, so if you specify error reporting directive to be set to this,0128

then all the fatal runtime errors will be reported.0136

There are other ones, like E_WARNING, which is sort of a step down from error; it's maybe nonfatal errors, but something that you should know about.0139

E_NOTICE is the next level down, which is even less severe errors that happen.0148

And as you can see, there are a number of different constants you can use 0154

in the error reporting configuration directives to set the level of errors that you want to see.0160

Down here, just to mention, is E_ALL, which shows all of the different errors and warnings; it is commonly used in development,0167

because you want to be made aware of any errors that are occurring.0176

The way that the error reporting directive works is by performing bitwise operations on these different error constants.0180

For example (and I'll explain what that means in a second), if we go and look at the php.ini file,0194

and we go down a little way and find the error reporting directive, this is an example of a bitwise operation on two error reporting constants.0200

We have the error reporting constant E_ALL and the error reporting constant E_STRICT.0213

This right here is known as the bitwise or operator; what it does is: it says, 0218

"We want to see you report all errors, and then also, in addition, any messages that are reported by E_STRICT."0223

E_STRICT provides additional information to you that is not necessarily errors, but that is useful during development.0229

We are not going to go over bitwise operators in detail here.0236

If you want to find out more information, we are going to include a link in the Quick Notes to the bitwise operators on PHP.net.0240

But you can also find, within the php.ini file, in this Error handling and logging section...it talks a lot about0248

the different error level constants that are available.0256

And it talks about how you can use these bitwise operators to customize what error levels you want to be made aware of.0259

For example, this right here is the E_ALL constant, and it is running a bitwise operation known as the and operation0270

on the bitwise operation not of the E_NOTICE constant.0284

What that is essentially saying is, "I want to be made aware of all errors, except" and this means to not...0292

"I don't want to be made aware of errors that are of the notice level"--so, it is saying everything but the notice level.0298

These are examples of how you can use these bitwise operators.0305

If we go and look at a script we have written called errorHandling.php, it is going to generate an error.0311

And in this case, we have created a variable called divideByZero, and we are going to have it be the results0322

of a division operation that divides by 0, which in PHP and most programming languages is not allowed, and it is going to generate a warning.0327

So, if we have this script, and we go and take a look at it (let me just refresh it), you can see that we get a warning.0335

It's of the error level warning; it is saying division by 0 occurred on line 14.0343

If we go back and look at errorHandling.php, see, on line 14, we divided by 0.0348

Well, if we want to, for example, configure our PHP setup so that it doesn't show warning messages,0354

which are configured by the E_WARNING constant, we can edit our php.ini file to change that.0360

What we are going to do is: we are going to say we want to show all of the errors, except we don't 0369

(and this is the not operator) want to see the warning errors.0374

If we save this, and then (because we are changing the configuration file, we need to restart Apache) if we go ahead and restart Apache,0379

and view our page again, you should see, because this error is of the E_WARNING type, it should disappear.0387

And as you can see, it does; let me just go back and change that back to the default value.0395

This is the default value that we have been using for development, and this is the default value that XAMPP sets in php.ini.0403

And we go ahead and restart Apache and make sure that the error shows up again; and we refresh the page; we can see that we get the warning again.0410

Now, one thing that PHP also provides is a built-in function known as the error reporting function.0423

It is specified here by error_reporting, and then parentheses.0431

And what it does is: it allows you to set, on a script-by-script level, or at the script level, the error reporting level that you want to be set.0436

So, for example, if you have your php.ini file, if you have the error reporting directive in there set to show all of the errors,0445

you can use the error reporting function on any particular script to...0455

For example, in this case down here, if we included this function call in our script, we could say, "We want to see all of the errors,0460

except for the warning errors," like we have just done.0466

And what that does is: whatever script we call that in, those are the only errors that are going to be reported for that script.0468

And so, what it does is: it allows you to override the global PHP configuration to set the error level to whichever you want.0475

For example, we can mimic what we have just done by changing the php.ini file in our script by adding this error reporting function.0485

And again, this is a function that is built into PHP.0497

And if we set it to "We want to see all errors except E_WARNING errors," and we save it, and then we go ahead and run our script,0500

which previously showed this error, and we run it now, because we have changed the error reporting level for this script,0514

using the error reporting function--we are not going to get the error anymore.0520

As we can see, the error disappears.0524

Let me go ahead and just get rid of this, so we can see the error again.0527

And you can see that, by eliminating that, we go back to the global setting for the error level, and our warning appears again.0533

There are a couple of other additional configuration directives you can use in php.ini to configure how error reporting is handled in PHP.0544

One of them that we are going to talk about is the display_errors configuration.0554

And basically, that is something that you set to either on or off; and that says whether you want the errors reported0558

to standard output, or (because we are developing web applications) if it is going to be output to the web page or not.0563

So, for example, when we looked at our last file, and we saw the divideByZero warning output to our web browser,0568

that was an example of display_errors being on.0575

There is also the ability to log errors to a log file, and there is a configuration directive for that called log_errors.0577

That is something that gets set to on or off as well; and that is something that lets PHP know whether you want to log your errors to file.0584

Something that goes hand-in-hand with the log_errors directive is the error_log directive.0593

What you set that to is the file name of the error log that you want the errors logged to.0599

So, log_errors turns on the logging, and then error_log specifies where you want those errors to be logged to.0605

There is also a track_errors configuration directive, and that determines whether a predefined variable called php_errormsg is made available to scripts.0614

We are going to talk about that a little bit more when we get to the error control operator.0626

If we go and go back to our php.ini file...and let's go ahead and turn the display_errors off, so you can see how that works...0631

if we turn this to off, and we restart our web server, whereas we previously saw this error, when we refresh the page,0640

we are not going to see it anymore, because the errors have been turned off.0651

Now, what we are going to do is go down to the log_errors directive, which is already turned on by default.0654

And what we need to do is set the error_log directive to the file where we want the errors logged to.0660

And if we scroll down, just a little bit further down in the php.ini file, here is the error_log directive.0667

And right now, you can see, by default, the XAMPP configuration has it log to this log file here,0672

which is a LINUX file path; and for that reason, it is not working in our Windows configuration.0679

So, if we comment that out, and go up and uncomment the line before it, which creates the error log file php_errors.log,0687

what that is going to do is: when we have any errors, now, it is going to log them to this file.0700

And the way this works is: because no path is specified, it is going to create this log file in whatever directory,0703

where we're running the script and it has errors.0710

So, now that we have added this, we save it and go ahead and restart our Apache server.0713

You can go ahead and look: this is the directory where the error handling script is.0722

As you can see right now, there is only the error handling script in there.0725

Now, if we go and reload the page, we are not going to see errors displayed, because we have turned display_errors to off.0728

But if we go and look at our directory, where the script is actually located, we can see that a php_errors.log file is generated.0736

And if we go ahead and open it up in PSPAD, we can see the error that is normally displayed.0744

It says "PHP Warning--division by zero," and then it goes on and outputs the rest of the message, saying it happened on line 16, and so forth.0749

That is an example of how the error logging works in PHP.0758

I'm going to go ahead and turn that back off and set it back to the default value that XAMPP had set up,0763

and then go ahead and also turn display_errors back on; and we'll set this value to on.0770

And when we go ahead and restart our browser, and we view the page, what we should see is that...0779

Well, first of all, let's delete this error_log file; now that we set log_errors to off, and display_errors to on,0788

we should see the error displayed on our screen, and we also should not see an error log file show up in this directory.0795

So, if we go ahead and refresh our page, we can see that warning message was output.0802

If we look back at our script directory, we can see, if I refresh it, there is no error log that was output.0808

Now, I want to talk about a new operator that we are going to introduce, called the error control operator.0820

It is an operator that is specified by the @ symbol, and what it is used for is to suppress 0825

any error messages that are generated by a particular operation or expression.0831

And the @ operator is a unary operator, and what it does is: it operates on whatever operand it prepends.0838

So, for example, in our script, we had this divideByZero variable; we set it equal to 1 divided by 0.0845

If we append this error control operator to the beginning of our variable, the error that is going to be generated0853

by this, this warning message of divideByZero, is going to be suppressed.0859

So, right now, we can see, if we refresh the page, that we are getting the warning about dividing by 0.0864

And if we go back to our script, and we add this error suppression operator to the beginning of the line,0870

we should see that the error is no longer going to appear; it is going to be suppressed.0879

And if we refresh the page, you can see: that, in fact, is true.0883

Now, the one thing that we had mentioned before is: there is a track_errors directive in php.ini, which can be set to on or off.0890

When that is set to on, it makes this predefined variable php_errormsg available.0897

What it does is: every time an error occurs, it stores an error message within this variable here.0905

You can use that variable to output it to your web page, or to wherever you want to output it to.0911

One thing to note is that it only stores the error message of the last error that occurred.0920

So, if you use this suppression operator, the error control operator, to suppress an error, 0924

you want to go ahead and output this error message in php_errormsg; you want to do that as soon as possible,0931

because any other error that occurs will overwrite the error message.0939

If we go back to our error handling page, we have suppressed the error.0942

And if we go ahead and echo this predefined variable, because our track_errors directive is set to on..and we go ahead and echo that...0947

now, instead of having no error output, we should get out what is reported by this error handling string.0960

And if we refresh the page, we see a message that says "division by zero."0967

That is the error message that was stored in the php_errormsg predefined variable.0972

So now, I just want to talk about the homework challenge for this lecture.0981

I just want to have you go through and mimic all of the different things that we have done today,0985

because it is going to give you experience with the different php.ini configuration directives.0989

It is going to give you experience using the error reporting function, which, again, allows you to adjust the error level on a script-by-script basis.0994

And it is also going to let you see how you can log errors, display errors, and also how the error control operator works in action.1001

The first thing I will have you do is create a script that is going to generate, like we did in our example, this divideByZero warning,1010

which, if you remember, is of the E_WARNING error class, and load the page to make sure that you are getting the error.1018

Then, I want you to go ahead and alter the error reporting directive in php.ini, as we did, so that the error doesn't show up.1028

And make sure you restart Apache and reload the page in the browser to make sure that the error doesn't occur.1035

Then, go ahead and direct the error reporting back to its default value, and reload the page to confirm that the error shows up again.1041

Then, like we did in our example, I want you to use the error reporting function to get the warning message to not be displayed on the script level.1050

So, use the error reporting function; reload the page to make sure the error doesn't show up; 1059

and then go ahead and get rid of the error reporting function, so that you can see that the error appears again.1063

Then, go ahead and set the display_errors directive to off, and restart Apache, so you can see how the errors aren't being displayed.1070

And then, I'm going to have you set the log_errors directive to on, and then specify a log file.1079

You can specify whatever log file you want; and reload the script, and verify that, because display is turned off, it is not being displayed, 1087

and also that the log file has been created, and that the warning was logged to your error file.1094

Go ahead and undo the process; turn error logging back off; turn display_errors back on.1101

Reload the page; make sure that the display is showing the error; and also confirm that your log file that you had before1107

doesn't have an update...well, 1) if you deleted it, that it has not been recreated, and 2) that if you hadn't deleted it, that it doesn't show the error again.1115

Then, to practice using the error control operator, go ahead and prepend the add operator to your divideByZero variable.1124

View the page to make sure the error doesn't show up, and then go ahead 1132

and use the php_errormsg variable to output that division by 0 error, so you can get practice using that.1136

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1144

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be introducing a bunch of new operators.0004

In particular, we are going to be introducing a group of operators known as the logical operators.0008

And we are also going to be introducing what is known as the ternary operator.0012

So, as mentioned, we are going to be talking about a number of different operators that fall under the class of logical operators0019

which allow you to create complex boolean test conditions, which are often used in if statements and so forth.0025

We are going to talk about how a couple of the logical operators are known as short-circuit operators, and we are going to explain what that means.0034

And then, finally, we are going to end up by talking about the ternary operator, which is a special operator in PHP.0041

As mentioned, logical operators are used to create complex boolean expressions, and they operate on boolean values.0051

The ones that are provided by PHP are the NOT operator, the OR operator, the AND operator, and the XOR operator.0060

What they do is: for example, the NOT operator is a unary operator.0070

And what that does is: whatever boolean value it acts on, it returns the opposite.0074

So, if the boolean value is true...if you prepend the NOT operator, which is the exclamation point, to a boolean value, 0079

it's going to return the opposite, so if you prepend it to true, it's going to return false.0088

If you prepend it to false, it is going to return true.0092

Then, there is also a binary operator known as the OR operator; it has two forms.0097

It can be used with two vertical bars, which are the same key on the keyboard as the backslash, typically.0103

And then, there is also the operator which is the or keyword.0109

Now, this, again, is a binary operator, and what it does is: it returns true if either its left or right operand are true.0114

So, it operates on two boolean values; so the only case it returns false is if both of its operands are false.0122

AND is the converse of the OR operation, and it also has two ways to specify that: double ampersands, and then also by the and keyword.0129

And it is a binary operator that returns true only if both its left and its right operand are true.0141

So, if they are not both true, every other condition returns false.0146

Finally, there is the XOR operator, which is known as the exclusive OR operator; and this is how it is specified in the code.0151

And it is a binary operator that is similar to the OR operator; it returns true if either one of its operands is true, but not if they are both true.0160

So, it's an exclusive OR: it can only be one or the other.0170

The OR and AND logical operators, as mentioned, have two different options.0176

The reason they have the different options (for example, the OR operator has the vertical bar option and the or option)0180

is because they have different operator precedences.0189

For example, the vertical bars have a higher precedence than the or operator, 0194

and the double ampersands have a higher precedence than the and operator.0199

The lower precedence versions are not used very often, and we are not really going to be talking about them much in this course.0204

The ones you will see will mainly be these double vertical bars, the or operator, and the double ampersand.0210

Now, just to talk, in general, about the precedence of all of the logical operators, from highest to lowest, they go this way.0216

Basically, the NOT operator has the highest precedence; then, it's the AND, the OR, and so forth.0223

And additionally, all the logical operators are left-associative, except for the NOT operator, the exclamation point, which is right-associative.0231

Let's go and take a look at a script called logicalOps.php that demonstrates these logical operators in action.0239

We are first going to talk about the NOT logical operator, which is the exclamation point.0248

And as we know, with if statements, an if statement evaluates a statement group if its test condition is true.0254

In this case, we have the NOT operator being prepended to the literal value false.0262

So, as we mentioned, it says the opposite truth value of what it is provided--of its operand.0269

Since it is not false, the opposite of false is true--this test condition here is going to evaluate as true.0275

So, this echo statement right here will be output.0281

Now, if we do the same thing using a boolean variable to show that it can work on variables, as well,0286

we can create a temp boolean variable, and we set it equal to true.0292

And then, we set the condition equal to !$tmpBool; so in this case, it's going to be "if not true."0295

And "not true" is always going to be equal to false; because this test condition will be false, this will not get executed.0302

And instead the else statement group will get executed, so this statement down here will be executed.0309

Now, to demonstrate the OR operator: as mentioned, the OR operator will return true any time either one of its operands is true.0315

So, using literal values, in these first three cases here, where we have either one of the operands as true, 0326

or in this case (the third case) both of the operands are true, each of these test conditions are going to evaluate to the expression true.0333

So, all of these echo statements within these if statements are going to get output.0342

Now, the only time the OR operator returns false is if both of its operands are false.0347

So here, if we have if false OR false, it's going to return false, and so, the else echo statement is going to be echoed.0352

Down here, this is the same exact thing with the same exact results, except it uses the lower precedence or operator.0361

But it demonstrates the same logical functionality, which is: if one or the other is true, return true.0367

For the AND operators, as mentioned, that binary operator only returns true if both of its operands are true.0374

So, in this first case here, if we say true AND true, that will evaluate to TRUE, and so this echo statement will be output.0382

In these other three examples, where we have true and false, false and true, or false and false--0389

all of those are going to return the boolean value false, because both operands are not true.0394

And so, in these cases, the echo statements in the corresponding else statement groups are what is going to be executed.0400

Down here is just, again, an example of the lower-precedence and operator.0409

It has the same logical functionality, only returning true if both operands are true; and this is just what it looks like in code.0415

Now, the XOR operator, which only has one version, returns true if either one of its operands is true, but not both.0423

So, in this case--these first two cases here, where only one of the operands is true--these if echo statements will get output.0433

However, in each of these cases, where it's true XOR true and false XOR false, both of those logical operations will return false.0441

So, the else echo statement will be output.0450

And down here, it just shows the results of these different operations.0455

Basically, it is the output from all of these if and else statements that we had up above, and basically saying...0460

It's like a truth table, explaining how these operators work--not false equals true; not true equals false; and so forth.0466

The OR operators return true, except when both operands are false.0472

The AND operators only return true when both of its operands are true.0478

And then, as we learned with the XOR operator, it only returns true when one of its operands is true.0483

Now, if we look at the code behind this (this is logicalOps.php--let's scroll down to the Code section)...for example, where we have0491

the OR operator, in the fourth demonstration of the vertical bar OR operator, we have an if/else statement.0504

It is saying, "If false OR false, echo this statement here; otherwise, echo this statement here."0512

Well, because false OR false is always going to be false, this statement here is never going to get echoed.0519

So, what we can do instead is use a combination of logical operators.0526

So, we can actually change this and get rid of the else statement by including the NOT operator.0529

And what we are saying is: if false OR false is not true (meaning it's false), then go ahead and evaluate the if statement.0537

So, in that case, we can get rid of this else statement and replace its output up here.0546

And this shows, again, a combination of using logical operators in combination with each other.0554

So, we have the first logical operation, which is false OR false, which is going to return the value false.0559

Then, we are performing the NOT operation on that false value, which is going to return true.0564

Therefore, this echo statement is going to return, which says false OR false equals false.0568

If we save this and go back and look at the page, down here in the results for the OR operator, we should see the same results.0574

And we refresh, and you can see that false OR false equals false.0586

That is an example of using a combination of logical operators.0589

Now, two of the operators, the OR and the AND logical operators, both versions of those operators, are known as short-circuit operators.0595

What that means is: if the value of their left operand, which is an expression, can determine the output of their operation,0602

then the right operand, or right expression, is not evaluated at all.0610

For example, with the OR operator, we know that it returns true any time either operand is false.0615

So, if the first operand--left operand--evaluates to true, there is no need to evaluate the right operand, 0621

because we know that the operation is always going to return false.0627

Likewise--or in the opposite way--for the AND operator, the AND operator, we know, only returns true when both of its values are true.0631

So, if the left operand, or first operand, is false, we know the AND operation is always going to return false.0638

And so, there is no need to evaluate the right operand or right expression.0644

So, if we go and look at a script called shortCircuitOps.php, we can see this short-circuit operation in action.0649

For the OR operation (and we are going to use the vertical bar version), if we create a variable called orTemp and set it equal to 0,0662

and then, we say, if true, orTemp=1, orTemp=1 is an assignment statement, and assignment statements, as we know,0671

are expressions, and they have a value; and the value of an assignment statement is the value that is being assigned.0681

So, this expression, if it were to be evaluated, would have the value 1.0687

So, if we go ahead and run this if statement here, because this first operand is true, that determines the output of the operation.0692

The OR operator is a short-circuit operator, so this second expression never gets evaluated.0700

The value of orTemp never gets updated to 1, so when we echo this statement down here that echoes the value orTemp,0705

it is still going to have the value of 0.0711

And if we look down at the bottom, we can see: orTemp equals 0 in this first example.0713

Now, let's say we switched the order around: the left operand always gets evaluated.0718

In this case, this is going to evaluate orTemp=1, so that means orTemp is now going to be updated--it is going to have the value of 1.0722

And then, it is going to say 1 OR true; and since that is always going to return true, then what you have is:0729

we are going to echo out the orTemp value, and we are going to see that it is actually going to update it, in this case.0736

So, if we look down here, we see that orTemp=1.0740

That shows how the short-circuit operation of the OR operator works.0743

Similarly, for the AND operator, if we declare a variable andTemp, and we set it equal to 0, and we have a logical operation0748

that is false, "AND"-ed with the assignment operation where you are assigning the value 1 to andTemp,0757

we can see that, as a result, andTemp is never going to get set equal to 1.0765

When this echo statement occurs, andTemp is going to output 0.0770

That is because we know that the left operand is false, so the AND operation is always going to return false.0773

There is no need to evaluate this left expression.0780

And as you can see, here we used what we had talked about in the last example, where we were combining logical operators.0784

Here we have an AND operation, false AND this assignment statement.0792

And if that returns false (which it is going to), then we can use the NOT operator; prepend that to that, and it's going to 0796

return it as true, which makes this echo statement evaluate.0804

If we look at the output of this if statement right here, we can see that andTemp is going to be equal to 0.0809

That is because this andTemp=1 assignment statement never occurs.0814

Again, as we saw with the OR example, if we switch the order of the operands on the AND statement,0818

this andTemp=1 assignment statement will always get executed, so the value of andTemp is going to get set to 1.0824

And because this operation is going to return false, and then we perform the NOT operation on that, which is going to return true,0833

this echo statement will occur; andTemp will be outputted; and here, we can see that it is output to the value of 1.0839

Now, we are going to talk about a special operator called the ternary operator.0848

Sometimes, it is also referred to as the conditional operator.0852

And as the name implies, it's a ternary operator, which is a 3-operand operator; and it is the only ternary operator within PHP.0856

And the way it works is (here is an example of what it looks like in action, down here): 0865

its first operand here, op1, is interpreted as a boolean expression, or a boolean value.0869

If it equals true, then (after the question mark is the second operand) the second operand will be returned.0877

So, whenever op1 equals true, this will be returned as the output of this operation.0885

If op1 equals false, then op3 will be returned.0895

And again, just to mention, it uses a question mark to separate the first and second operands, and the colon to separate the second and third.0905

So again, if op1 is true, the second operand is the output of the ternary operation.0913

If op1 is false, the third operand is the output of the ternary operation.0918

Let's take a look at a script that demonstrates that, ternaryOp.php.0925

Basically, what we have here is a ternary operation where we have a variable result, and we are setting it equal to the output of a ternary operation.0931

And here, we can see, a ternary operation has the question mark, the colon, and the three operands.0940

We set the first operand to the literal value true; so because it's true, we know from what we just learned0946

that the ternary operator outputs the value of the second operand.0953

So, in this case, the result is going to be set to the second op; and when we output the result, it is going to say secondOp.0956

And if we look down here, we can see: this first output is output=secondOp.0962

Likewise, if we instead set result equal to this ternary operation, because the first operand is false, 0967

the output of the ternary operator is going to be the third operand; in this case, it's the string thirdOp, so our output is going to say the string thirdOp.0974

And in fact, that is what it does.0983

Now, one other thing you can do is: this uses literals, but to demonstrate--you are typically not going to be using literals0987

as the first operand in a ternary operator; you are going to be using variables and combinations of variables,0993

using comparison operators, logical operators, and so forth.1000

Here, if we declare a variable, temp, equal to 1, and then we run the comparison operation temp=1 1003

(and this is, again, as we learned from our lesson on comparison operators, the equals operator),1010

and it returns true with both values on each side of it, both of its operands' values are equal.1014

So, temp=1, so 1=1=true, so it is going to output the second operand, which says "temp=1."1020

And we can see down here, outputted, it says "temp=1."1026

Now, if instead we go ahead and set temp equal to 0 and run the same ternary operation and store its output in result,1030

this is going to evaluate 0==1, which is going to evaluate to false, because 0 is not equal to 1.1038

So, the third operand is going to be output, which in this case is a string that says temp not equal to 1.1045

And we can see our output down here; it says temp not equal to 1.1051

I just want to quickly talk about coding conventions as it relates to these different operators, particularly the logical operators.1057

Basically, PHP is always going to abide by the rules of precedence and associativity as it evaluates different expressions.1065

For example, this if test condition here and this if test condition right here actually evaluate to the exact same boolean value.1071

It is a combination of two logical operators--a logical AND and a logical OR operator.1083

However, this one has parentheses around the AND operation.1090

Now, the AND operation has a higher precedence, so when this statement up here gets evaluated, this operation will always occur first.1093

The result of that will be "OR"-ed with the a operation.1103

Now, down here, the same thing happens, except we explicitly put in these parentheses.1106

What that does is: even though the parentheses aren't needed, it makes the code a little bit easier to read and a little bit easier to understand.1111

So maybe, if somebody is reading your code that is not as experienced in PHP and in working on it,1118

they can intuitively know that, "OK, this AND operation is always going to happen."1123

And it goes along the lines of: if you can make your life easier by adding just a few extra things,1126

then why not take the extra step to go ahead and add these extra parentheses.1131

So, in our examples in this course, we are always going to add extra parentheses to make it explicitly clear1135

which order the operation is going to occur in, even though it's not necessarily necessary.1142

For today's homework challenge, I'm going to have you create a script that accepts two GET variables--one called sex and one called age.1149

For this challenge, I want for the sex variable to either take on one of two values: male or female.1158

And then, let age represent the age of a user, and have it take on the values between 1 and 99.1164

And I want you to add a single if statement to your script; and this is to practice using the NOT operator.1171

And it is going to test if the sex GET variable is not equal to male; then, it should output a message that says, "The user's sex is female."1177

And what you can do to test this out is to manually edit GET query strings, using both of these name/value pairs, sex=male and sex=female.1187

Make sure you are only getting your output message if the sex is listed as female.1196

Now, I want you to alter the if statement, so that, instead of having its NOT operation, it is going to have an OR operation.1202

And what I want it to do is output true any time the age provided is less than 25, or if it's greater than 50.1209

And if that condition is met, you should output a message that says, "The user's age is not in the 25-50 age range."1219

The way you can test that is to generate test queries where you set age equal to three different values, 1228

to make sure that the test condition is completely evaluated.1234

You set it once equal to a value less than 25, once equal to a value greater than 50, and once to a value in between 25 and 50.1239

And when you run these test queries, the only time that you should see output is when the user's age is not in the 25-50 range.1248

Go ahead and test that and make sure that it is running correctly.1257

Then, I'm going to have you expand your test condition even further, and this is to get practice with using combinations of logical operators.1261

We are going to include an AND operator; and I want the test condition to check if the user is not between 25 and 50, and they are also a male.1269

So, it is going to output a message, if this condition is met, that says, "The user is a male not in the 25-50 age range."1279

And the way you can test that is to use the same query strings that you used in step 5 up here,1289

with a different age provided to test the three different age groups.1294

But then add the name/value pair sex, once with the value male and once with the value female.1300

And you should only see the output when the sex is equal to male.1307

And so, that is going to give you practice working with a combination of logical operators--in this case, the AND and the OR operator.1311

Again, as we had mentioned, the AND always has higher precedence than the OR operator.1316

But practice, when you write your code, using extra parentheses in there to make it explicit to anybody that looks at your code1321

exactly what order the operations are occurring in.1327

Then, I want you to just go ahead and remove the if statement from the script.1332

And we are going to get a little practice with the ternary operator.1335

I want you to create a variable that is an output of a ternary operation, and the ternary operation...1338

the first operand is going to be a test to see if the sex is female.1343

If the sex variable provided by GET is female, it is going to set the variable value to "the user is female."1348

If it's not, it is going to set the variable value to "the user is male."1357

And when you do that, remember that, if the test condition of a ternary operator--the first operand is true, the second operand is output.1361

And if it is false, the third operand is output.1368

The way you can test this is by generating two query strings, one with sex=female and one with sex=male.1371

And what you can do is run this script with both of these query strings, and make sure that you get the correct message output.1378

When you provide sex=male, you get an output that says "the user is male."1388

When it says sex=female, you get the output that says "the user is female."1392

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1397

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be continuing development of our web application, 0004

incorporating some of the concepts we have learned in our last few lessons.0008

First, we are going to start off by reviewing what our last version of the web app looked like, which was version 6.2.0014

And then, we are going to go through 2 revisions in this lesson: we are going to upgrade to a version 7.0 and a version 7.1.0020

Now, in version 7.2, one of the things I want to note is that we don't actually do any GET data validation.0028

So, for example, on checkout.php, item.php, and thankYou.php, all of those scripts accept GET parameters.0037

And what they do is: they access the data in those GET parameters, without really checking to see if they are available.0048

As a result, if you go directly to any of those pages, you get a warning from PHP saying you're trying to access a GET variable that doesn't exist.0054

And in addition, the page doesn't work as it is supposed to.0062

For example, if we go and look at version 6.2--and here is what it looks like if we go to store.php (let's decrease it a little bit)--0065

but if we were to go, for example, directly to checkout.php, you get an error at the beginning saying "undefined index items."0082

That is because we are trying to access, in our code, the items array.0089

And, for example, if we go directly to items.php, we are going to get an error, as well.0094

And if you will notice, none of the item information actually shows up down here on the screen, 0101

saying that you are trying to access an item ID that wasn't provided.0106

And if we go and look at the code, for example, for this page (this is the 6.2 version of item.php),0110

we can see the second statement in our code--we create a variable called currentItemID, and we set it equal to _GET['itemID'].0118

Now, instantly, because if we go to item.php without providing an itemID GET variable, this is going to generate an error,0130

because this variable doesn't exist, because it wasn't passed in.0137

And, in addition, because we use this currentItemID variable in different parts of our page to look up item information from the catalog,0141

none of that is going to work, as well.0148

So, it has the implications of generating an error, as well as not allowing the script to function as it should.0150

What we are going to do is: in version 7.0, we are going to make use of if/else statements that we learned about.0160

We are going to use the isset construct that we have learned about.0165

What we are going to do is some basic validation on our GET variables.0170

What we are going to do is: we are going to test that any GET variables that are required by a particular script0173

(in this case, checkout.php, item.php, and thankYou.php)--we are going to verify that those variables actually exist and were passed in.0178

We are going to do that using the isset function.0189

And if they are not set, we are going to set them to null, by default.0192

Then, what we are going to do is: when we do this process of checking to see if they are available,0196

we are going to create short forms of these GET variables, which is something that you commonly do in PHP,0202

because it's a lot easier to write, for example, dollar sign, item ID, than dollar sign, underscore, GET, square brackets, item ID.0207

So, it is a way to make it easier to use the variables within your code, without clouding it up with unnecessary syntax.0216

We are going to create these short variables when we validate them, and then we are going to 0224

use them to conditionally output the HTML content of the page.0227

And what that means is: if the appropriate GET variables were provided, we are going to output the content of the page, as we are supposed to.0233

If not, we are going to output an error message.0241

And one thing in particular we are going to do is: we are going to make use of our logical AND operator, 0244

which we learned about, in the validation of our GET data for thankYou.php.0249

We are also going to divide each of these three pages into different sections, and we are going to use comments to do that.0256

What that is going to do is separate out functionality of the page, and it makes the pages easier to understand.0262

When you go back and look at the pages, you will know, "OK, the top of the page is where the GET variables are always processed."0267

"At the bottom of the page is where the HTML output always occurs."0272

Let's go take a look, first, at item.php; and this was the old item.php; and let's see what it looks like in an updated version.0276

At the top of the page, we have added a new section; and the way I have demarcated a section 0286

is just by adding this comment tag that says "process GET variables."0292

And what that is going to do is: this section is going to be used to create the short variables for our GET variables,0296

and also to check to make sure that they are valid.0303

So, for example, we have our if/else statement, which we just learned about a few lessons ago.0306

And we run the isset function on _GET['itemID'].0311

And if _GET['itemID'] exists and it's set, then we set currentItemID to that value; if not, we set it equal to null.0315

Then, what we go ahead and do is: in a previous section, if you look at our old itemID, after we have made 0324

a short version of our GET variable, we did a little processing on it.0330

For example, we look up the current item in the item catalog; we set the page title for the page.0333

Well, I've created a section called Perform Any 'Global' Data Processing; in this section...0339

these sort of actions that occur after the short GET variables are created--this section will contain them.0344

And you can see, there is another if/else statement in here, and it is going to make use of the fact 0352

that we have created the short variables, and we have validated whether or not they are actually input.0357

For example, to avoid that error that we got on previous pages, what we have done is checked to see 0361

if currentID was not equal to the null, because if the ID was set to null, that means that it wasn't passed in.0369

And if it was, then we go ahead and look up the item in a catalog (and actually, this line shouldn't even be here), 0376

because we have done that up here--we have created the short variable up here, at the top of the page.0383

And so, what this tests is if the current ID isn't equal to null, that means it was passed in, and it is set to the value itemID that was passed in.0387

And then, we can look up our item in the catalog, and we can set the name.0395

However, if this statement evaluates to false, which means that it was null, which means that an ID was not passed in,0398

then we are going to set the page title to say error.0405

Down here, we have created a section called Output HTML, and this is where all of the HTML is going to be conditionally output from now on.0409

That is going to be based on this data processing that occurred at the top of the page.0418

For example, now, whereas before we just would output the HTML header in our old version, 0422

and then go straight ahead and output all of the information about the item,0428

we have a conditional statement, an if statement, that says "if current itemID is not equal to null," which again,0433

references the fact that it was passed in, "then we go ahead and output all of the item's information."0437

But we add an else statement at the end, so if itemID is equal to null, which means it wasn't passed in,0444

then we output an error message that says "you have reached this page in error."0449

If we go and look at...again, this is what item.php looks like on version 6.2, you get these errors, and that is because we haven't provided a query string.0453

For example, if we went ahead and provided...then we get the functionality as expected.0465

Well, let's go back and look at the new version, 7.0.0473

And now, when we go directly to item.php, we actually get an error message.0478

And that is because it is processing the GET variable and saying, 0482

"OK, you didn't actually present a GET variable called itemID, so we are going to generate an error."0486

Now, we have also done this for the other pages in the website, for the other pages that take GET variables--for example, checkout.php.0492

If we go to checkout.php without any GET variables, we get the same message, "you have reached this page in error."0500

And if we manually go to thankYou.php, we are going to get a "reached this page in error," as well.0506

If we go back and look at the code--let's look at the code for checkout.php, for example--0515

you can see, we have added this section again, up here at the top, about processing the GET variables.0522

We performed a similar isset test on the GET variable items to make sure it was passed in,0526

and if not, we set our short variable, cartItems, equal to null.0532

Then, if we go down here to do our data processing--in this case, because the checkout script actually calculates the total,0537

if our cartItems is not equal to null (which means that a valid GET variable was passed in), then we go ahead0546

and do the calculations, because if we didn't have a valid GET variable, there is no reason to try and calculate them.0551

And then, we have the else statement that says, "If the cartItems is equal to null," if it wasn't passed in, "then we are going to output an error page."0557

Down here, we have the HTML Output section, and again, we have an if statement that tests0566

whether or not the short GET variable exists, meaning that it was passed in.0571

If it does exist, we go ahead and output the shopping cart total that was calculated in the processing section,0576

and the form that accepts information about the customer's shipping and billing address.0582

Now, if there was an error, meaning that the GET variable was not passed in, then instead, we would output an error message,0589

which you just saw, which is "you have reached this page in error."0596

Now, in thankYou.php, we have the same similar concept, except that in thankYou.php, there are two GET variables that we access.0599

We access the variable customer and _GET ['orderTotal'], and actually, I can see here that it is supposed to have this in here.0612

What this does is: this checks that the customer GET variable was set, and (and this is where0630

we are making use of the AND logical operator) that the orderTotal was set,0640

because we want to make sure, before we access these variables further down in the script, that they are available.0647

And if not, we set them equal to null.0653

Here, we have created the short form of the variables.0655

And then, down here, in the data processing section, we have our logical operator again, AND.0660

It is saying, "If both customer data is not equal to null, AND order total is not equal to null, then 0665

we are going to go ahead and set the page title to thankYou, and that is going to mean that we are going to process the page as normal."0672

If either of these were equal to null, we are going to generate an error, and here we set the page title equal to error.0679

Then, we have the Output HTML section; again, we have the conditional test to decide whether to output0685

the regular HTML of the page, the regular HTML content, or an error message.0692

And the test we have, again, is if either of the GET variables...if both of them were not equal to null, meaning they both existed,0697

then we are going to go ahead and output our order information, like we have done before,0705

where we output the date of the order, the sales tax that was used, the order total, and so forth.0708

And then, also, we echo the address.0715

And if not, we have the else statement down here that says "you have reached this page in error."0717

And so, that was what we saw when we looked at these pages in the browser.0723

For example, again, if we refresh thankYou.php, we get an error, whereas let's say we go through the application as we are supposed to--0727

and go to Complete Order: now, our thankYou page was output as appropriate,0749

because you can see, at the top here, we have the appropriate GET variables that were passed in from the form.0753

And this is the page we had developed in the last lesson.0758

So now, we are going to change things a little bit: we are going to upgrade to version 7.1.0764

And what we are going to do in this lesson is make a couple of simple changes.0769

We are going to replace the if/else statements we used to process the GET variables at the top of the page.0772

And we are going to replace them with simpler and cleaner-looking ternary operations.0778

I'm going to show you that in a second.0782

Additionally, we are going to add the error reporting function to our config.php file, 0784

which, as you know, is the configuration file that we include in all of our pages on the website.0789

What that is going to allow us to do is: because we are developing, we can go into that config.php file 0794

and override the global error reporting settings that our PHP configuration has set up.0800

That will give us flexibility, while we are developing, to experiment with different error levels.0807

And also, it does it in an easy way, because we don't have to edit php.ini, and we don't have to restart Apache.0811

So, in this one, we are actually going to be editing the config.php to make that change, to add the error reporting.0818

And then, in these three here, we are going to be updating the way that the GET variables are processed to use ternary operators.0823

Version 7.1 is going to look the same as version 7.0, and if we go to the thankYou page or checkout page--0838

go to any of these pages directly, we get the error, as we are supposed to.0848

However (let's see--let's pull up another...), this is an old version--the 7.0 version of thankYou.php, and if we go ahead0851

and open up the 7.1 version, at the beginning of thankYou.php in 7.0, when we process the GET variables,0862

we have this if/else statement up here, and it's saying that if these variables are set,0873

then go ahead and set their value to the value that was passed in; if not, set that to null.0877

We can do that a little bit more simply using ternary operations.0881

Instead of that if/else block, we can set customer data, and we set it equal to the customer value that was passed in,0886

if isset ($_GET ['customer']) is true (that means if it was passed in), we set it to the value; and if not, we set it equal to null.0896

Likewise, for orderTotal, if the order total was set, if it was passed in, we set the value of the short variable orderTotal0902

equal to the value that was passed in; and if not, we set it equal to null.0910

As you can see, this cleans things up a little bit, and makes things a little bit easier to read, and it's a pretty simple operation.0913

That is how we use the ternary operators; we do that on item.php and checkout.php, as well,0921

where we have replaced the if/else statement at the top with a ternary operation in0931

checkout.php--for the cartItems short variable and for currentItemID in item.php.0935

So, as mentioned, the other change that we made is: we added, at the bottom (this is the top)--0943

if we go all the way down to the bottom of config.php, we have added a section for error reporting,0948

and we have added this error reporting function, which, as we know, overrides the default PHP configuration's error reporting level.0952

And in this case, we are going to set it to development value E_ALL OR E_STRICT, 0962

which means output all error messages, and then also, in addition, any notices that fall under the E_STRICT category.0967

This is the value that is set by default in the XAMPP php.ini file.0975

What we are going to do, to make this error reporting function do something useful, 0981

is go ahead and edit our php.ini file to make it more restrictive, to put it on, for example, a production value.0985

Or, in this case, we are going to set it to the default value, which says "I want to report all errors, except for the notices--except for E_NOTICE."0995

And that is different from E_ALL or E_STRICT, because in the E_ALL or E_STRICT, the notices get output.1005

So, in this case, when we set this global file like this, and we go ahead and restart Apache,1013

it is going to have this new error level that is going to report less errors.1021

And so, now, when we go to our config.php file, because this is included in every page, it gets set back to this development level.1026

Now, in the real world, you may or may not do this; you may actually just go ahead and edit the php.ini configuration file.1037

The point why I'm putting that in here is to get practice with using this error reporting method,1043

and to see how it can be used, because maybe sometimes you won't have access to the php.ini file on whatever server you are working on.1048

And so, this will allow you to be able to do that.1056

And so, that is how we make use of the error reporting function.1059

For today's homework challenge, I just, as usual with our web application lessons, want to make sure that you understand the different things.1063

So, the first thing is to make sure that you understand why we added the simple GET input validation to our scripts.1071

And that was because that way, we don't get any warnings from PHP saying we are trying to access data that doesn't exist.1077

And also, it causes our scripts to not malfunction--like, for example, the item.php page that tried to access data that didn't exist.1083

And you could see, there were blank images; it didn't output the price; and so forth.1093

And we made use of the if/else statement within our item.php page to only output the item's information 1097

if we know that an item ID was properly passed in; otherwise, we output an error.1105

Also, I just want you to consider how dividing the page into different sections--and this will probably become a little more evident1109

as we move on to future versions of the web application--based on functionality makes it a little bit easier to understand.1116

When you go to the file now, you always know that, in the current setup, the bottom section is going to always be where the HTML output occurs.1125

So, you know that, if you are going to be looking for any HTML output (maybe you have an HTML output area),1133

you are going to be looking down at the bottom.1137

We know, at the beginning, there is the section where we process and create our short GET variables.1139

And then, there is a section where we do data processing; and what that is doing is preparing the data for output in the HTML.1144

So, if maybe some of our data is bad, then we can know to go look in the Data Processing section.1150

That just makes things a little bit easier to maintain and debug, and aids other people that could end up reading your files, as well.1154

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1162

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be introducing some more conditional control structures.0005

In particular, we are going to be introducing the elseif and the switch statement.0008

As mentioned, we are going to introduce the control structure that is called an elseif statement,0015

which is used in combination with an if statement, which you have already learned about.0020

We are going to learn about a switch statement, which allows you to evaluate different statements, based on the value of a certain variable.0026

And we are going to talk about something known as the default case, which applies to switch statements.0034

And then, we are just going to quickly go over coding conventions, as it relates to these two types of control structures we are introducing.0039

An elseif statement is a conditional control structure that you can associate to an if statement, like an else statement that we had learned about.0048

The difference between an else and an elseif statement--one thing I should mention, again, 0056

is that an elseif statement is technically not a statement, as far as PHP goes, but that is commonly what it is referred to as.0061

The difference between an else and an elseif statement is that the elseif, if the test condition for the if statement is false,0067

has another test condition it evaluates, and it only evaluates its code segment if that is true.0078

For example, this is an example of an if statement combined with an elseif statement.0083

Here, we have if, and then test condition 1--if test1 is true, the if statement group gets executed, and execution continues down to the bottom.0089

Now, if this test condition equals false, instead of going down to an else statement, we go down to an elseif statement.0102

And this provides another test that we evaluate, 0109

and then this section associated with the elseif statement only gets executed if test2 is equal to true.0112

So, it allows us a way to allow another test condition to decide what type of code or which section of code to evaluate on.0119

So again, this section is only going to get evaluated if test1 from the if statement was false, and then test2 was equal to true.0129

One of the nice things you can do with elseif statements is: you can chain multiple elseif statements together.0137

And you can do that as often as you need it.0144

In this case, we have an if statement with two elseif statements appended to it.0147

And the same rules apply as we just talked about: for example, this statement group only gets executed if test1 is false and test2 is true.0153

However, if it comes down here, test1 is false, and test2 ends up being false, it goes on to the next elseif block and evaluates test3.0162

If test3 is equal to true, then it evaluates test3's statement.0170

However, if none of the test conditions apply, then you just exit the entire control structure set, 0175

and you continue with whatever statement is next in line.0181

Let's take a look at an example of the elseif statement in action.0188

For example, this is a script I have written called elseif.php, and it accepts one GET variable called num, and you set that equal to a numerical value.0195

And what we have is a couple of elseif statements that will conditionally execute or echo a statement,0207

depending on the value of the number that is passed in.0215

For example, the first test is if num (and in our code, we have num as a short variable created for the GET variable num)0217

is equal to null (which means it wasn't passed in); then, we echo "no number was provided."0226

If num is less than 0, we write, "the number provided is negative"; if it's greater than 0, we write "the number provided is positive."0230

If none of these conditions are met (which is only the case if num equals 0), then we just move on to the next statement, which would be down here.0238

So, let's go ahead and show you how this works.0246

If we go ahead and put num=...well, first of all, actually, let's just look at the page where we don't put any input.0248

We haven't included any num statement: down at the bottom here, we can see the results.0260

This first result here applies to this first elseif statement: we can see the message "no number was provided,"0264

which means that num equals null, and this section was executed.0270

Let's go ahead and enter num=100, which is a positive number.0273

When we do that, what is going to happen is: this code that is going to be entered is going to say, "Is num equal to null?"0282

It's going to say false; num is equal to 100; "Is num less than 0?"--that test is going to return false.0289

And it's going to go down here and say, "Is num greater than 0?"0297

100 is greater than 0; this is going to evaluate to true, so this echo statement gets executed.0299

If you look down at results, it outputs that statement, "The number provided is positive."0304

Now, if we go up here, and we change this num to equal -100, and we hit Enter, the same process is going to happen.0309

num is not going to be equal to null, but what it is going to do is: when it reaches the first elseif statement,0317

it is going to say num is less than 0--that is going to evaluate to true, so this echo statement is going to be output.0322

And then, because this condition was met, this following elseif statement doesn't even get evaluated.0327

This test condition never gets evaluated, and execution would jump immediately to the following line of code.0332

If we look at the result, we can see "the number provided is negative."0338

Now, one of the things that we can do, as we can do with an if statement, is: we can add an else statement to a group of if and elseif statements.0345

And what happens is: the else statement group gets executed if none of the conditions in the original if,0354

or any of its associated elseif, statements evaluate to true.0360

And this right here is an example of this sort of structure.0365

It has an if statement, followed by an elseif statement, followed by an else.0370

What happens is: if test1=true, it goes ahead and evaluates this group and jumps to the bottom down here.0375

and evaluates the next line of code after all of these structures.0382

If test1 is false, it goes down here and evaluates condition test2.0385

As we know from what we learned about elseif, if this is true, then this statement group gets executed, and again, we would jump out to here.0390

Now, if test1 is false, and we go down here and test2 is false, then else gets executed, no matter what.0399

And in this case, it is going to execute whatever the else statement group is.0407

So, if we go back and look at our elseif.php file, we have another section of elseif statements here,0411

except--it is exactly the same as before, except we have added an else statement here.0417

And what we had talked about before was that this first group of if, elseif statements--0421

they will always enter at least one of these statements, unless the number is 0.0427

So, in this case, if it is equal to null, the first one is executed; if it's negative, the second one is executed; if it's positive, the other one is executed.0431

But if it is 0, it is going to be none of these; so in this case, we can add an else statement.0439

It says, "If you get to this section, the number you provided is 0," and it's going to say "the number provided was 0."0442

So, if we go ahead and input the number 0 and refresh the page, we can see two things.0449

We can see 1) the output for this bottom section with the else statement says "the number provided was 0," and that is because of our else statement.0459

We also can see that nothing was output for the first section of ifelse statements.0466

That is because 0 met none of these conditions: it wasn't equal to null, it wasn't less than 0, and it wasn't greater than 0.0470

So again, these elseif blocks only get evaluated if one of their conditions is true.0478

If not, execution just jumps to immediately afterwards.0482

The next control structure we are going to introduce is known as the switch statement.0489

What that does is: that compares a single test expression against a number of different values, which are called cases,0493

and then evaluates any statements associated with those cases.0502

For example, this is the syntax of what it looks like.0506

It's a switch keyword, and then it is followed by an expression in parentheses.0509

In this case, it's a variable called num that is going to hold a number value.0515

And then, what you can see here is: within the switch statement, which is denoted, 0521

as with the other control structures, by curly braces, it has a number of different cases.0526

It has case here, which is 1, that says, "If the value of num is equal to 1, then you process these statements here."0531

"If num is equal to 2, then you process these statements here."0542

"If num isn't equal to any of these, none of them get processed, and execution jumps out to the end of the script."0546

Now, one thing to note is that the case values (here is another example) can only be scalar values.0556

So, they can be strings, integers, bools, and floats.0564

Or, they can be the value null; they can't be things such as arrays and so forth, or objects.0570

Also, what happens is: on the last slide, you will notice that, 0576

after each statement in our case statement, we had a second statement that was break.0580

This break statement is a special statement, and what it does is: the way switch operates is:0586

you input a value or expression, and then it goes down linearly from top to bottom, evaluating each case, and saying,0592

"Is the value passed in equal to this case?"0599

And then, what it does is: once it finds a case that matches, it goes ahead and runs every statement, 0603

until it either reaches a break statement or the end of the switch statement.0608

So, in this case, because there is no break here after the first case statement, if the name passed in is the string joe,0614

what is going to happen is: it's going to say, "OK, I match here, so I'm going to evaluate this case."0621

"I'm going to evaluate this statement here," so it's going to echo "name is joe."0625

But then, there is no break statement; and as mentioned, the switch statement continues to execute statements0630

until it either reaches a break statement or the end of the switch statement.0634

So, there is no break statement here, so what it does is: it goes down here; it is going to output this line, as well.0638

It is going to echo "name is john"; then it is going to reach the end of the switch statement, and it's going to stop.0643

So, this is probably not the behavior that would be desired, and so that is where break statements come into use.0647

Typically, to make this function as we would want it to be, we would add a break statement below here, and then a break statement below here, as well.0655

Let's take a look at some code examples using the switch statement.0671

Let's go to switch.php, which is an example file.0679

And here, we have a switch statement that uses, as its value to compare against, the value of the variable called phone,0683

which, for this script, is a short variable for a GET variable that is passed in called phone.0695

We are going to have, for this script, that phone can take on the different string values home, work, or cell.0703

And so, what happens is: if we were to pass in a GET parameter, in this case, in this original page, we just have switch.php0711

with no query string, so phone is going to get set equal to null, because we have used a ternary operator to process the GET variable.0717

And the way we do that is: if the GET variable phone is set, we set it to the value; if not, we set it equal to null.0726

So, if nothing is passed in, we go down here; we reach the case null; it is going to echo "no phone number was provided."0733

And then, you notice the break statement here, which means none of the rest of these statements are going to get evaluated.0739

And so, it is going to jump to the end of this switch statement and break out of it, which is where the name "break" comes from.0748

If we look down at our results for the first output, it will say "no phone number was provided."0752

Now, for these other ones, it has a case for if you provide home; it's going to say "the phone number provided was home,"0759

"phone number provided was work" if you provide the name work, and so on for cell.0763

So, if we just go through and try out some of these...we'll say phone=home; you can see, down here at the bottom,0768

it says "phone number provided was home," and that echoes this statement right here,0775

because when phone variable was passed into this switch statement, it didn't match null, but it did match home.0780

And then, just to do one more as an example, we'll put in cell.0787

What is going to happen is: this switch statement is going to get evaluated; phone is going to be compared to null;0791

in this case, it's the string cell, so this is not going to be evaluated; it is not going to be equal to home,0798

so this case and its associated statements are not going to be evaluated.0802

It doesn't equal work, so this is not going to be evaluated; and then, at the same time, it does equal cell, so this one is going to get evaluated.0807

So, when we refresh the page, if we go look at the bottom, we can see "the phone number provided was cell."0814

Now, one other scenario: let's say we provided something that said cell2.0822

Maybe this is a script that processes different phone numbers, and it said, "I want to update my phone, cell2."0828

If we go ahead and enter that, you will notice that there is no output here.0834

That is because, when phone equals cell2, and it enters the switch statement, the switch statement is going to compare0839

the string cell2 to each of these different cases.0848

Because it doesn't equal any of these cases, none of these statements gets executed.0850

That is going to bring us to another interesting point we are going to talk about, which is called a default case.0855

This is similar to an else statement that gets appended to a series of if, elseif statements.0864

What that does is: it uses the keyword default, and what it states is that if you enter the switch statement, 0869

and you compare the expression passed in (in this case, the variable num), and it doesn't match any of the cases,0879

then by default, it is going to always run this statement group here.0886

So, in this example, if num equaled, for example, the integer 2, we would come down here, and we would say,0891

"case equals 0; 2 doesn't equal 0"; it wouldn't evaluate this.0897

It would compare 0 to 1; that would evaluate to false, so it wouldn't echo here.0901

Then, when it reaches the default section, and it says, "Well, it hasn't reached any of the others of these,"0905

we are always going to go ahead and output this here.0908

And we can make use of that in our script to go back here and...here we have a switch statement.0912

For this part right here, it is the same as we had before in this top example, except we have added a default case.0920

And so, what that is going to do is: as you notice, when we entered cell2 as the value of phone, 0926

you can see that nothing was output for this top if statement, because it fell through all of these cases and had no default output.0933

But down here, we have a default case that says, if you compare phone to each of these cases, 0941

and it doesn't match any of them, then you go ahead and output this default statement.0947

In this case, we are just echoing the statement that says "the phone number will be set to home."0950

And as you can see, that is what happened.0954

Just quickly, we are going to talk about coding conventions.0959

For elseif statements, the same coding conventions are going to apply as we use for if statements,0963

as far as parentheses and spaces and curly braces go.0968

The switch statement, also, is going to have similar code formatting.0971

If we go and look at the code, the one thing you will notice is: like with our if statement, 0976

there will always be a space between the switch keyword and the opening parentheses of the test condition.0980

The opening curly brace will be on the same line as the switch statement, and there will be a space between that and the closing parenthesis.0986

In addition, each case will be indented one indent further in, or one indent deeper, than the switch statement.0992

You can see, all of these cases are indented one further.1001

And then, under each case statement, all of the statements that are part of the case statement group will also be indented one, relative to the case.1004

So, you see here, we have three different indent levels.1013

Finally, the closing brace, like our if and elseif and else statements, is going to be on a line all by itself,1017

and it is going to be aligned at the same indent level as the switch keyword.1023

The other thing we want to mention is that when we use a default case in our switch statements, we are always going to put it as the last case.1033

Now, technically you don't have to do that, but that is typically the convention, and it makes sense,1040

like with our ifelse statements--else is always at the bottom.1045

Well, with a switch statement, we are always going to put the default case at the bottom.1048

And additionally, we are always going to add a break statement to our default case.1051

Now, technically, because the default case will always be at the bottom, as we described, whenever its statements are done executing,1056

it is going to reach the end of the switch statement, and so it will stop executing,1063

because we know a switch statement executes everything from the case it matches until it reaches a break or end of statement.1067

That said, we are always going to include that break statement.1072

That would be for reasons...in case somebody decides to add an extra case at the bottom, below our default statement, or something like that.1076

It is just to improve the robust-ness of our code.1082

For the homework challenge for today, I want to have you create a script that accepts one GET variable named action.1088

We are going to let action take on one of three string values: one, two, or three,1095

which correlate to three different actions that a script might perform.1100

I want you to use the ternary operator, like you had used in our web application, to create a short variable called action1104

that gets set to the value that was supplied for action, if it was supplied.1112

It gets set to null if no value was provided.1116

Then, I want you to use a set of if, elseif, and else statements to do three things.1119

If no action was provided (which would be action is equal to null), then you provide an error message saying "no action was provided."1125

If the value is one to three, then I want you to output a separate message for each of those, saying "action1 will be performed";1135

"action2 will be performed"; "action3 will be performed."1141

If action is specified, but is has an action name that is not one, two, or three (for example, let's say the user specified action=four),1145

then I want you to output a message saying that some default action was performed instead.1152

Be sure to test these conditional statements that you create.1160

And you can do that by...you should use the name/value pairs name=one, name=two, and name=three 1165

to verify that you definitely get the output that says "action1/action2/action3 was performed."1171

as well as providing something where it says name=xxx, where xxx is not one, two, or three 1176

(in this case, as we just mentioned, we could say name=four).1182

The other thing is: you also want to not provide the variable name.1191

And actually, this is a little bit of a typo; these actually should be action=one, two, or three.1198

So, the other thing you should do is not provide the action variable at all, and you should output the message corresponding,1203

where it says "no action variable was provided."1211

Then, what I want you to do is go ahead and convert that if, elseif, else statement group all into one switch statement1215

that has a default case (and remember, the default case sort of corresponds to an else statement).1221

And then, test your switch statement with the same inputs you used up here in test 4, and make sure you get the same output, as required.1229

Be sure to format your elseif and your switch statements according to the course's coding conventions that we had talked about.1237

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1244

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be covering the topic of nested conditional control structures.0005

Specifically, we are going to be learning about what a nested conditional control structure is and how to use it.0012

We are going to talk about coding conventions as they apply to nested control structures.0018

And then, we are also going to go over how to debug conditional control structures:0023

especially once nested gets involved, as you will see, they can become quite complicated.0030

So, we are going to provide some debugging tips for you.0035

Nesting control structures means that, within the statement group of one conditional control structure, you include another conditional control structure.0039

For example, if we have an if statement with its test condition, and then its opening brace,0049

these opening and closing braces define the statement group of that if statement.0056

Well, within this if statement, we have included another conditional control structure--another if statement.0061

And then, within this if statement, we have included another conditional control structure, this statement.0069

These actually should be indented one further.0077

And so, what you can see is that, in PHP, there is no limit to the number of levels--how deep you can nest control structures.0081

And what it allows you to do is to achieve fine-grain control over the execution of conditional segments of your code.0090

For example, maybe you have a section of code that you want to run if someone is a female, their age is over 25, and they are over 60" tall.0100

In this case, the code we would execute would be "you are a female over age 25, over 5 feet tall."0109

Using nested control structures like this allows you to achieve that sort of fine-grain control, 0116

to only execute code based on if multiple conditions are met.0123

Let's go and take a look at a script I have created called nested.php.0129

And what it does...before I get into this stuff here at the top, let's look at the code for it.0135

It takes two GET parameters: one called function and one called arg.0140

function can take on one of three different values: date, toUpper, or toLower.0149

What that is going to correspond to is the date function, the strtoupper function, and the strtolower function, which we learned about.0156

arg is going to refer to an argument that you would pass to these functions.0163

In our script, by passing a function, the function name by the function GET variable, and the function argument by the arg GET variable,0170

what we can do is set up our code so that it will run the specified function on the argument that was requested.0180

The first thing we do is: using the ternary operator, we create short versions of our GET variables; we call one function and one arg.0187

function, again, is the name of the function, and arg is the argument we will be passing to it.0195

Then, we have a couple of nested control structures.0200

So, the first test we do is: we test if function was not equal to null--so that is saying, "Was function provided as a GET variable?"0204

If that is true, then we go ahead and proceed into that if statement.0211

If not, we are going to output a message and say, "No function was selected."0215

Now, once we get in here, we perform another test with an if statement: is argument not equal to null?0219

So, if function wasn't equal to null, but argument was, then we are going to output a message that says no function argument was provided.0224

If not, we are going to go ahead and enter the if statement group.0232

Within this if statement group, which we enter if function is not null and arg is not null, what we have is a switch statement.0235

It runs over the variable function, which is the name of the function passed in.0244

What it does is: it compares that name to each of these three different cases: date, toUpper, and toLower.0249

If it matches any of those cases, what it is going to do is: it is going to run 0256

that corresponding function with the argument that was passed in by a GET.0259

And if an argument was passed in, but the function name is not one of these four--it is not one of the ones recognized--0266

then it is going to, by default--its default case is going to output a message that says "invalid function was requested."0273

What I have up here is a form I have created that uses the GET method.0279

It makes testing these out a little bit easier; and you can see that it has the three functions selected for which this code can process.0284

If we look at the source code for this, we can see that this Select dropdown box has three options 0294

whose values are date, toUpper, and toLower, which match those cases in our switch statement.0303

So, if I select date, and I pass an argument to it, we know the date function outputs a formatted date,0310

and it does so based on a formatting string we provide to it.0318

And so, I want to output the day, the month, and the year; one way to do that is with the characters j M Y.0321

And if we go ahead and click the Call Function button, we can see that it outputs the current date, June 27, 2011.0328

Likewise, if we do strtoupper, and we pass it a lowercase string, and we call the function, the result we get is turned to all uppercase.0337

Now, if we use the strtolower function, and we put an uppercase string, and we call it, it is going to convert it to lowercase.0350

So, as you can see, by passing in the function name and an argument value, and then using this set of nested control structures,0361

here we have a switch statement nested within an if statement, nested within another if statement.0369

What we do is: we compare one of the GET variables (in this case, function) to a bunch of different cases.0375

And then, we use the other argument, the other GET variable passed in, to go ahead and run a function based off of that.0380

So, that is how you can make use of nested conditional control structures.0388

Now, I just want to talk about coding conditions that we are going to use for nested control structures.0395

The way it is going to work is: when you nest a control structure within another one, 0401

you are going to indent the entire nested control structure one indent deeper than the enclosing structure.0406

And we saw that here in nested.php--if we look at the code of that, we can see that here, we have an if statement,0412

and within that, we have nested a switch statement.0420

And as you can see, the switch statement is one indent further than the enclosing control structure.0424

And that said, when you do indent, when you do nest a control structure, the same indentation rules should apply for that control structure.0433

For example, we know that for a switch statement, all of the case statements are one indent deeper than the switch keyword.0441

So, when we nest a switch statement within an if statement, we still indent all of these one extra indent.0446

By the time we get down to these statements here, based on our rules that we have, we have this break statement 0452

that is indented four indents deep: one for this if, one for this switch, one for this case, and one for indenting the case statements.0457

So now, I just want to talk a little bit about debugging control structures.0474

As you can see, when you start adding a lot of nested control structures, the code can get very complicated.0476

You get a lot of test conditions, a lot of curly braces, a lot of semicolons, a lot of break statements...things that are easy to mess up, on occasion.0481

So, debugging them can be quite challenging.0493

Common questions you might be asking yourself are, "Why is the code in this if statement not executing when it is supposed to?"0496

"I have supplied the inputs that I thought were supposed to make it happen; why is it not happening?"0502

On the converse of that, "Why isn't the code in a particular if statement executing?" which is right here.0506

And some of the common errors that occur in our control structures are incorrectly specifying test conditions for your control structures,0512

for example, an if test condition; forgetting a break statement in a switch statement; and then also0520

one that can be the most deceiving is incorrectly placing or omitting an opening or closing curly brace.0527

Let's look at the first one, incorrectly specified test conditions.0534

If we go back to our nested.php...let's say we misspelled date here--we put date1, for example.0538

If we go to our code (this is the code behind nested.php), and we change date to date1 and save it,0547

and we refresh the page, now when we go up here and we try to run our date function, and we try to output a formatted date,0556

and we call the function--instead of getting a formatted date, we are getting "invalid function requested."0570

Why is that? Well, what happened is: we specified a function called date.0575

However, when we went through our switch statement (and actually, this is not the updated version,0582

because this was hard-coded into the HTML; let's go look at the code), what is going to happen is: it is going to have a function value;0587

it is going to have an argument value; when it enters the switch statement it is going to have,0594

the function variable is going to be set to date, and it is going to be looking for date.0598

It doesn't find it here, because we have mistyped it; it doesn't find it here; it doesn't find it here.0602

So, what does it do? It outputs a default statement, which says "invalid function was requested."0606

That is one way where misspelling a test condition can cause problems.0610

Another one could be if we leave out a break statement.0617

For example, let's say we leave out the break statement here.0620

We know from what we learned about the switch statement that, once a case is matched within a switch function,0622

every statement is executed until a break or the end of the switch statement is reached.0629

By leaving out the break statement here, what is going to happen is: if we select date, and it matches,0634

we are going to echo this statement, and instead of breaking out of this switch statement and back into whatever statement follows it,0640

we are going to go down here and execute the next line of code it finds, which is this echo statement.0646

So, this statement is going to be echoed, as well; then, it reaches a break, and it's going to break out.0652

We save this, and we refresh it, and we try to run the same thing as before.0657

Now, we have corrected...well, it looks like it already did it, but let me do it anyway...0666

What is going to happen is: we call the function; it is going to output the date, as we expected.0673

But then also, what it is going to do is: it is going to output that next line of code, which as we saw, was strtoupper.0679

What it is going to do is convert that argument we passed in, which was a date formatting string, and just capitalize it and output it.0685

And this could go even a step further: let's say we forgot to include the break statement here--then it is also going to call the strtolower function.0692

So, if we refresh this page again, which is going to submit the same GET values, we can see, it also added it in lowercase.0700

So, that is one error that can also happen with control structures.0707

Let me go ahead and fix these back, and save it and reload it, just to make sure everything is working as normal.0711

OK, I'll test out one of the functions; OK, so everything is working as it is supposed to.0726

Those are the two problems that can often happen, that we just looked at: incorrectly specified test conditions and the forgetting of a break statement.0736

Also, you can incorrectly place or omit a curly brace, which can cause a lot of problems.0745

It makes it hard to figure out what is going on, because PHP is going to give you an error, but usually the error says "error occurred on line 21."0752

But maybe the error actually didn't occur on line 21; it occurred earlier in the file--and I'll show what that looks like now.0758

If we go and look at, for example...we are going to look at this script called debugTest.php.0765

If we go and look at it in the code, we have the same form at the beginning that allows us to select a function and an argument.0777

And then, what it does is: we have a similar code as in the nested.php, except we'll just remove this inner switch statement.0790

And instead of the switch statement, I have just put an if statement that always evaluates true, and instead of 0799

calling the function, it just outputs a lot of sample text.0807

And the reason I put...you will see why I put so many sample text lines here in a minute.0810

When I go ahead and run this form, what it should do is: if I pass it a valid function name and a valid argument,0815

it should reach here and output all of these sample lines of text.0822

So, if we go and look at debugTest, and I call the function j M Y (it is not even a matter of what I put in, because0825

we are not calling the functions anymore), and press Call Function, you can see, it outputs all of these lines of sample text.0833

Now, one error that is common, that can cause a lot of problems, is: let's say we forget this last closing brace for the if statement.0840

We save it, and you might look at it, and everything might look OK, so we go ahead and we run the file.0848

And if we refresh the page to run it again with the same values, we are going to get an error.0854

It says you have an unexpected error on line 76; so if we go and look back here, the error that we omitted was all the way up here.0859

But it is saying the error is occurring on line 76.0868

Now, the reason that that is happening is: if we look at this from the PHP Interpreter's point of view, for this internal if statement,0872

once it reaches this opening bracket, it evaluates all of these statements as being part of this if statement.0880

When it reaches the first closing bracket, it says, "OK, I am done with this if statement."0886

Then, when it reaches the next closing bracket, it is going to say, "I'm done with this statement here."0891

And in this case, because there wasn't a third closing bracket for this if statement up here, when PHP reaches the end of the file,0897

it is going to say, "Hey, I never received a closing brace for this if statement up here."0903

It is supposed to see three different braces, and that is why it points to the error down here, because it works inward out,0907

in that it sees, "OK, this if statement was closed; this if statement was closed; but this first one wasn't."0916

So, even though we omitted the curly brace on this most internal if statement, it is generating an error for out here.0922

And as you can see, the error says "unexpected end"; and what that is meaning is that it reached the end of the file,0930

and it was looking for a closing curly brace for this if statement.0937

So, that is one error that can really deceive you, because you might be looking at it and saying, "Well, there is no error on line 76."0941

And the reason is because it is a brace that was maybe omitted...0948

And the reason I put several sample text lines here is to demonstrate 0951

how it is going to show the error on a line way down further from where it occurred.0956

For example, this is something that can happen, and it may throw you an error that doesn't make sense, and that is why:0963

because you may have omitted a curly brace 100 lines prior in your code.0969

So, if we go ahead and put this curly brace back in and appropriately close that if statement, and we run it again,0973

everything should work out fine; and there it is.0978

One of the useful techniques you can do for debugging conditional control structures is tracing the execution of your code, 0985

which is kind of what we did, where we look through the code, and for example, we looked at debug.txt.0991

Or actually, if we go to nested.php, we can say, "OK, let's say we provided a function and an argument variable as GET variables."0999

So, we would trace down our code, and we would say, "OK, start here; function is not equal to null."1008

"OK, I'm in here," and we're going to proceed further down; "Argument is not equal to null; I enter here."1013

Then we go to function, and then we go through and evaluate what the different case statements are and say,1018

"OK, is it compared to date?" If it does, we echo this, we break out of it, and then we break all the way back out to the beginning.1023

That is tracing through your code and visually reasoning where the code is going to progress.1030

One trick you can do is to include echo statements at the beginning of each conditional statement, or conditional control structure, 1037

or switch case, with a brief message that is going to let you know that the statement group or case was entered.1044

What that is going to do is (and you only use this when you are debugging, because it is going to output messages 1051

that you wouldn't want to see on a production site): let's say you know that 1055

you are evaluating an if condition that is three if's deep within your file.1060

If you put a debug statement at the beginning of every time you enter an if statement,1066

then you know that, when you look at your output when you run a test--you should see three debug statements.1070

And if you don't, it gives you a clue: if you only see one, or if you only see two, it gives you a clue as to maybe where your error is occurring.1075

Maybe you are not entering a particular if statement--when the debug statement doesn't show up, 1081

you can say, "Well, why didn't I enter this if statement?" and it can clue you in to where that error is happening.1086

So, if we actually go back and look at another file called debugging.php, it is the same file as nested.php,1091

except that it has debug statements added.1099

So, if we go to debugging.php, and we look at the code, we can see that, starting from the first if statement,1105

after each if statement was entered, we output a small statement that says "debug: function was not equal to null," because that is this test condition here.1112

And then, once we enter the second if statement, we say "argument not equal to null."1122

Then, for each case, so that we know when we have entered a case--we have matched a case in our switch function--1126

we also echo a debug statement: this one says, "OK, we are calling the date function."1131

Here, we are calling the strtoupper function.1135

What that will do is let you trace through and make sure you are going through all of the conditional control structures 1138

that you are supposed to, meaning that this test condition here was met, 1143

this test condition here was met, and this test condition here was met, for example, if we were using the date function.1146

If we go back now, with these debug statements included, and we run our code,1153

and call the function, we see the output of our debug statements.1161

We can see the first one, debug: function is not equal to null; so that tells us, "OK, we have successfully gotten to this first if statement."1165

debug: argument not equal to null--well, that debug statement means that we got into the second if statement.1173

debug: calling date--that means that we matched the date case in our switch function.1180

And so, therefore, we know that we have gone through and met all of the test conditions that we were supposed to meet for our script,1185

and that provides a way of giving us feedback, in case there is an error.1191

For example, if I go back over to...once again, go to change this date to date1 so that it doesn't match, so we have an error there,1195

and we save it and run the script again, two things are going to happen.1212

One is: we are not going to get the formatted date; we are going to see an unexpected debug statement,1218

saying the default case was reached (which--we are going to wonder, "Why is that?).1223

And then, we are going to see "invalid function requested."1226

If we go back and look at our code and trace through that (and let's look at the actual code),1228

well, in the output, we first saw that function not equal to null and argument not equal to null debug statements were output.1236

So, we know that we have entered this if statement; we know that we have entered this if statement.1243

The next debug statement that occurs in our output is "default case reached."1248

Let's continue tracing through the program; we are in this if statement; we enter the function statement.1253

We should be hitting this debug statement here, but instead, we are outputting "default case is reached,"1258

which means we are reaching a default case, which means that, for whatever reason, the value that we expected 1263

to match the date case up here didn't match.1269

And sure enough, if we go ahead (this will clue us in) and say, "Wait a minute, why didn't the date case match?"1272

OK, we had a typo on the date; and what that will allow you to do is: then you can go back and refresh the page,1276

and you can see that it is working now.1285

And so, that is a way to help you debug very complex nested control structures.1287

It is quite a useful technique of just outputting simple debug statements, as they are called, 1292

while you are in development, to make things easier, to figure out what is going on.1298

For today's homework challenge, I want to have you do something kind of similar to what we did today1303

with our script that allowed you to select a function and an argument.1307

And it is going to accept three GET parameters: one called operation, one called leftOp, and one called rightOp.1311

What these are going to refer to: operation is going to refer to one of the four basic arithmetic operations.1317

leftOp and rightOp are going to refer to left and right operands of an arithmetic operation.1323

We are going to let operation take on one of four different values: it can be add, subtract, multiply, or divide.1329

And in this case, we are using these abbreviated strings.1337

And so, what is going to happen is: if it receives a leftOp and a rightOp variable from GET, 1341

and it receives an operation that is one of these four values, it is going to perform that operation on these values.1347

Now, what I would like you to do is have it output an error message if no operation is provided1353

(so operation would be equal to null, if we are using the short variables that we have been using with the ternary operator),1358

it is going to output an error message in both the leftOp (and that is the keyword here, AND, which is going to imply a logical operator),1366

AND rightOp are NOT provided (NOT also--that is going to denote a logical operation.1372

Then, it will also output an error message if you provide an operation value, but is not one of the four that are allowed.1382

And then, finally, if the user tries to divide by 0, I want you to output a message.1390

Your solution is going to look similar to what we did today with the nested.php example.1395

in that you should be using nested if, else, and switch statements, and your switch statements should make use of the default case.1399

That will allow you to achieve all of the functionality we have just described.1406

And then, what you need to do is test each of the different cases.1411

Supply some different variables, leftOp, rightOp, and operations; you are going to test 1414

that all of the different operations work (addition, subtraction, multiplication, and division), 1419

along with providing different variable leftOp and rightOp numbers to make sure that they are performing the operations.1423

The other thing that you are going to do is: you are going to try to divide by 0, to make sure that you get that divideByZero error.1431

And then, after you have done that (or if you are having problems figuring out how to get it),1436

I want you to go ahead and add debug statements to each conditional structure, like we did in our example today.1440

So, once you enter each if statement, add a debug statement that says "debugging if statement number 1."1445

And then, also do that for each case in the switch statement.1451

So, for example, if you hit the case add when you are comparing the variable operation against a number of cases,1453

and you compare it against add, when it hits that case, you would output a debug statement saying "performing the addition operation."1462

That will give you practice using the debug statements.1470

And then, just one other note is to be sure to indent your code properly, and make sure you are not missing any curly braces or break statements.1473

And just follow the coding conventions that we have talked about in today's lesson.1481

Thank you for watching; I look forward to seeing you next time.1486

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be continuing developing of our web application,0005

incorporating what we have learned about nested control structures to improve the application.0008

Specifically, we are going to review what was the state of the application as far as the last version, which was version 7.1.0015

We are also going to introduce a new construct, called empty, 0022

which is useful for form validation and making sure that data was provided to a form as needed.0027

And then, we are going to go over two new versions of our web application, versions 8.0 and 8.1,0034

in which you are going to use nested control structures to add some features.0042

First, as we talk about 7.1: in 7.1, we added some simple GET input validation.0047

And what we did was: we just used the isset method to check whether a particular GET variable we were going to use was supplied or not.0055

However, we didn't really go any farther than that, as far as validating that the data that was input was valid,0063

and was what we needed, and was the right type of data.0068

So, that is what we are going to expand on in this version 8.0.0072

For example, in our checkout form, we are going to make sure that at least one item was selected in the Shopping Cart.0078

And when we go to our thankYou page, when we go to complete our order, 0084

we are going to make sure that the user provided all of the necessary shipping and billing information.0089

Before we do that, I do want to talk about the empty construct, though.0094

This is a built-in PHP construct that is used to determine if a variable is "empty."0100

And it is useful, as I mentioned, for processing form data, to make sure 0107

that specific GET variables were provided to a script, and that they actually had a value.0112

What it does is: it takes a variable in as its argument, and it returns a boolean value, either true or false, 0120

based on whether the variable is considered empty or not.0126

So, the empty construct will consider a variable to be empty if 1) it has not been declared (kind of like the isset statement),0129

or if it has been declared, but it has a value of any of these values: if it's equal to the empty string,0142

the integer or float equal to 0, the string 0, false, null, or an empty array.0149

Let's take a quick look at a script here called empty.php that shows the use of the empty construct.0158

Here, we have a ternary operation, and we run the empty construct on the variable tmp.0165

As we just mentioned, empty returns a true or false boolean value, as to whether or not the variable is empty.0173

As you can see, up here we have commented out the declaration of tmp.0180

So, when empty runs on it, it should return false, because the variable hasn't even been declared yet,0186

because we know, with the ternary operator, that if this evaluates to false, the third operand is going to be output.0193

So, what this variable result does is: it is our way of storing a formatted output of the empty variable,0199

because the empty variable returns a boolean value, in that a true converts to a string (to a 1), and false converts to the empty string.0207

If we just output the result of empty($tmp) directly, it wouldn't look that pretty.0216

So, what we are going to do is: based on whether empty returns true or false, 0225

we are going to set the output string result to be either the value true or false.0229

So, if we run this script with this variable tmp not declared (and let's open a new link), when we go to empty.php, we can see empty($tmp) is equal to true.0233

And that is because we haven't declared the variable yet, which means it's empty.0251

Let's go ahead and declare it, but it still doesn't have a value; so in this case, empty should still return true, because it doesn't hold any value.0257

If we go and refresh the page, we should get the same output; and we do.0269

Now, if we go ahead and set empty equal to 200, for example, it is no longer going to be empty, because it has been declared,0274

and it has a value that is not equal to one of those empty values we mentioned.0283

And if we save the script and reload it, we should now get that empty is equal to false.0287

However, let's say we go back and set tmp equal to 0; or actually, let's set it equal to the empty string,0293

which sometimes happens when users submit a form and don't provide any data in a text input field.0303

So, it's the empty string, which we know is one of the empty values considered to be empty by the empty construct.0311

We should get, now, that the value of empty($tmp) is equal to true.0316

So, if we refresh the page, we can see, "OK, tmp is considered empty, because it contains the empty string."0324

So now, we are going to talk about the changes we are going to make to version 8.0.0334

As it mentioned, we don't have that great validation of GET input data validation going on in 7.1.0339

So, we are going to add some validation to make sure that at least one item is in a user's Shopping Cart.0346

I'm going to add that to checkout.php; to thankYou.php, we are also going to add some validation, to ensure that0352

any necessary shipping and billing information was provided--making sure they provided a first name and a last name 0360

and all of the parts of the address, except for the apartment number, because not everybody has an apartment number.0366

And the validation--we are going to make use of the empty construct that we just learned about0370

to make sure that 1) all of the shipping information inputs were provided, and also that they weren't left as empty.0375

because they might be returned as a blank, as an empty string; and isset would return true,0383

but it would be considered empty, because no value was provided.0391

The other thing that we are going to do is: we are going to be introducing two variables, a boolean error flag0395

(and a "flag" often refers to just a boolean variable that flags a certain condition),0401

and then we are also going to define a variable that holds an error message.0406

And we are going to add that to our three scripts, checkout.php, item.php, and thankYou.php.0412

What that is going to do is make our error processing more efficient--for example, when we find an error 0418

because a GET value wasn't provided, or if a GET value was provided, but it wasn't validated as we needed.0422

Let's go take a look at some of the scripts from this web application.0429

For example, if we look at...this is checkout.php from version 7.1, which is our last version...if you can see, at the beginning,0437

it processes the GET variable; it creates a short form of it.0445

And then, what it does is: it goes right into...as long as the GET variable is not null, which means as long as some item value was provided,0448

it is going to go ahead and start calculating the total or the subtotal.0458

Now, that doesn't really provide any validation to items, making sure that valid input was provided.0463

So, we are going to take a step further, because...one reason is: why bother calculating the total of a cart,0468

for example, if the user did not add any items to the cart?--for example, if all the items were selected at quantity 0?0474

What we are going to do is: we are going to nest an if statement in here that is also going to check0482

to make sure that at least one of the quantities is greater than 0.0487

So, if you go look at our new checkout.php version, 8.0, we can see, we have the same processing of the GET variable at the beginning.0491

We can ignore this error section for now; we'll talk about that in a second.0500

We have the same if statement that checks to make sure that cartItems was at least provided.0504

But then, we have nested another if statement that has another test condition that must be met.0509

And that says that at least one of the items in the cart (either 1001, 1002, or 1003) has a quantity greater than 0.0514

And if that is the case, then it goes ahead and executes this section, which calculates the total.0522

If this condition is not met (meaning that all of the values were 0, or the quantity was 0 for all of the items in the cart),0527

we are going to end up using this error code; it is going to output a message that says, "You need to add at least one item to your cart."0535

Now, what we have done up here is: in this data processing section, we have added two variables.0543

We have added an error flag, and we initially set it to false.0548

And what that is going to do is: any time we encounter an error, such as a GET variable was not passed in at all,0552

or it was provided invalid data, we are going to set error to true.0558

And then, we also are defining a variable errorMsg and setting it to empty string,0563

which is going to allow us to create a custom error message that we can use to output.0571

And the reason for creating these variables is because, at different points in these nested if statements,0577

we are going to have the possibility of generating errors.0582

Let's say, for example, one thing that we do when we generate an error is: we want to set the page title equal to error.0586

Now, if we went down here, and we did that every time we encounter an error, we would have to, in this else statement, write pageTitle=error.0593

And then, we would have to also repeat that down here, and do that for each error.0607

And as our pages get more complicated, and there are more error conditions, we might be doing this four or five times throughout a page.0615

That gives us four or five times to have an opportunity to maybe misspell error.0621

And we know that, any time we have code that is being used in multiple places,0625

we want to see if we can reuse it by putting it in one spot.0632

So, instead of having these page titles here, every time an error is generated, we set error equal to true.0635

In this case, it was true, because the cart was empty.0645

And then, in this case, we are also adding a custom error message that says "You must add at least one item to your cart before you can check out."0651

Down here, this else statement corresponds to if cartItems was equal to null, which means it wasn't supplied at all, so it was a GET error.0659

In that case, we just want to output what is our default message, which is "You have reached this page in error."0667

What we do is: we don't need to define a custom error message, like we did up here.0672

We can just set the error value equal to true, and then once we are out of the data processing section, or towards the end of it,0676

we have added a little section of code that is going to allow us to, for example, define this page title all in one spot.0683

It is going to, if error is true (meaning that an error condition happened), define the title for the HTML title tag to error.0690

And then, what it is going to do is: if the error message is equal to the empty string, 0697

meaning that a custom error message wasn't set (because up here, for example, we set a custom error message),0704

then it is going to output a default error message that says "You have reached this page in error."0710

Now, what we have also done in our code is: in our previous version of checkout.php, when we got to the Output HTML section,0715

we just checked to see if our GET value was equal to null.0723

If it wasn't, we output the checkout form, as would be expected.0727

And then, if there was a problem, we would say, "You have reached this page in error."0733

Well, now what we are going to do is: instead of comparing it to whether cartItems is equal to null, we are just going to say, "Did an error occur?"0737

"And if an error did not occur (we are using the NOT operator), then go ahead and output the checkout form, as expected."0744

Then, we have an else statement that says, if an error did occur, to output the error message.0751

Now, as we saw up above, the error message can be either set to the default error message (and is, in one of the examples) or a custom error message.0757

By using this one error message variable to hold either a default message or a custom message, 0765

we can simplify this to one line of code down here to output our error message.0772

We also did this for thankYou.php; for thankYou.php (and this is the new version, 8.0), as you can see,0777

we have added this error flag and this errorMsg variable to the data processing section, just as we had done in our new version of checkout.php.0789

This is the same code that we had in version 7, that just tests to make sure that the GET data, customer data, and order total were provided.0801

But then, we have added a nested if statement that is going to further validate our input.0808

Basically, we have an if statement here that says, "It is only going to enter the if block," which in this case, 0814

just sets the page title equal to thankYou, meaning that there is no error--"it is only going to do that if all of these conditions are met."0822

Using the empty function, if customer data's firstName was not empty (and we say not with this NOT operator),0830

AND if their lastName was not empty...and we do that for city, street, state, and zipCode--0837

the only one we don't include is apartment, because not everybody has an apartment number...0843

we are only going to output the Thank You message if the user entered all of the appropriate information, 0846

which is everything except for the apartment number.0853

If not, in the else statement, we are going to set an error, and it is going to set the custom error message,0855

"You did not provide all of the necessary billing and shipping information."0862

And then, here again, we are making use of this error message and error flag functionality by...0869

this section is reached if neither of these GET variables were provided.0877

And that is just going to output the default error, which is "You have reached this page in error."0883

Here we have the same error processing section we did on checkout.php.0887

It is going to set the page title to error in the HTML title tag.0891

If no custom error message was created, meaning that errorMsg is still equal to the empty string, then we say, "You have reached this page in error."0896

Now again, when we get to our HTML output section, we test the condition "did an error occur?"0905

If no error occurred, then we go ahead and output the Thank You message, as we normally would on a correctly-entered form.0910

If not, we go ahead and output the error message, which would either be 0919

"You have reached this page in error" or "You did not enter all of the appropriate data into the form."0922

And we also had done this for item.php, as well, in that we added the error flag and the errorMsg to process the error.0933

In this case, the only error that occurs in this file is if the currentItemID is not equal to null,0946

because we are not doing any other validation on the itemID, whereas in the checkout, we validated0951

to make sure the cart had at least one item in it, and the thankYou page--we validated that all of the shipping information was provided.0957

But we did update item.php, as well.0965

Let's close some of these down.0969

So now, to version 8.1: what we are going to do is: we are going to be altering checkout.php,0974

so it not only handles the requesting of the shipping and billing information 0981

that happens when a user says Check Out from the viewCart page,0986

but we are also going to have it output the Thank You message0991

So, we are actually going to get rid of the thankYou.php page altogether, and we are going to have checkout.php do that.0993

The way we can do that is: now that we have conditional control structures and have nested control structures,1000

we are going to create a GET variable called action that we can provide to checkout.php.1006

And based on that variable, we can determine what function we are going to perform, and what we are going to output.1011

In our case, if the action variable is set to checkout, we are going to know that the cart was just submitted.1018

We are going to calculate the total in the cart, and then output the shipping information.1026

The other option that we have for the action variable is Complete Order.1031

After the shipping information has been output, and that form is loaded from the viewCart.php page,1038

what is going to happen is: checkout.php is going to submit the shipping and billing information to itself,1046

so the action attribute of its form tag is going to change.1053

Whereas, before, it forwarded that information on to thankYou.php, now it is going to forward it to itself.1058

It is going to append to that form an action variable that says completeOrder, and then it is going to know to say,1063

"OK, now I am processing a Thank You message," and process the data accordingly and output a Thank You message.1070

All we are doing is taking all of that functionality out of the thankYou.php page and putting it in checkout.php.1077

And there are different schools of thought on this: this is a common way of doing things--1084

by providing an action GET variable to a script that lets it complete different actions,1091

based on what you specified as the action you want completed.1098

The other way is to just, instead of having multiple actions be completed on each page, where you conditionally output HTML 1103

based on the action that was specified--you can have one page just forward the information to another, and on to another.1110

So, for example, viewCart forwards to checkout.php, which would forward it on to thankYou.php.1116

In this case, we are having checkout.php forward the shipping information to itself.1122

And as you will see in the advanced course, when we push things out even further,1128

after you submit shipping information, then it is going to want to request credit card information, for example.1132

We are going to have a different action for checkout.php that is going to allow us to process that, as well.1138

And so, some people like doing each one on a separate page; some people like having an action GET variable1143

that allows you to specify the different actions all in one page.1148

And the reason I am showing it and doing this way is 1) it can be useful and 2) it is something that is used out there often.1153

And as you will see when we start introducing our own user-defined functions, these incredibly long scripts that we have because,1160

for example, if we have three different actions that occur on the same script, we have three different sections of HTML to output.1167

So, that means we have three if, elseif statements to go through.1174

You have the content of three pages in one script; that can get kind of lengthy.1177

When we create user-defined functions, it is going to make things a little bit cleaner,1181

and there is not going to be so much code in all of these pages.1186

Let's go and take a look at the change that we made.1189

This is our old checkout.php from the version we just did, version 8.0.1194

At the beginning, it has one GET variable that it processes, cartItems.1202

And then, it does the check to see if it's null and to see if at least one item in the cart had a quantity greater than 0.1209

And then, it outputs the HTML accordingly--either outputs an error message or outputs the shipping form.1219

In our new checkout.php, we have a new GET variable called action that we are going to process up here, using our ternary operator.1224

And what we have done here is: because now, this checkout.php form is going to perform both the check out operation, 1237

and it is going to perform the thank you operation, it is going to be accepting not only the cartItems' GET data when the action is check out, 1244

but when we go to thank you, which is specified by the setting action to completeOrder, 1253

we are going to need to have access to the customer data and the order total, 1259

which is the information provided by that shipping and billing form that we have.1262

So, at the top of this page, we have added two extra short GET variables.1266

Additionally, when we get to our global data processing center, because now we have to do two sets of data processing1275

(we have to process the data if a cart was submitted from viewCart.php and calculate the total,1282

and if the shipping information was entered and now forwarded to checkout.php, we have to be able to process that1289

and make sure that data was valid), what we do is: we create a set of if, elseif statements that look at the action GET variable.1296

And if it's checkout, it is going to perform all of the operations that were already in our checkout.php to begin with.1308

It is going to check that the cartItems is not equal to null; it is going to check that at least one item in the cart had a quantity greater than 0.1312

But we are adding another elseif statement that is going to say, "If action is equal to completeOrder," which means1320

that checkout.php is going to submit its shipping information to itself, then everything that was on that thankYou page,1328

all the data processing that was involved there, is going to happen here.1336

So, it is going to verify that customer data and order total were provided.1339

And earlier in the script, we saw that we have added those short GET variables to our script.1344

And then, it is going to perform the same data validation that thankYou.php had provided in version 8.0,1350

which is to make sure that all of the required fields for a shipping and billing address aren't empty.1355

And then, it is going to set the page title flag to Thank You.1360

You can see that we have used the same error handling mechanism that we had done before, where if an error occurs--1363

in this case, you did not provide all of the necessary shipping information--it is going to set it to true,1370

and it is going to set a custom message.1375

And as you can see, in this code, because we have even more nested statements, there are going to be more error situations that can occur.1377

So, we would have a lot of redundant code if we output pageTitle=error in each error section.1388

So now, we see the value of declaring this error boolean flag, and then the error message,1396

because it allows us to put a simple message error=true when an error has occurred.1401

And that will know to default to the output message.1407

Additionally, when we set it equal to true for all the errors, when it reaches this error processing code, it is going to set the page title equal to error.1409

The other thing is: we are going to add one more depth to the Output HTML section, as well.1420

We have the same check as before if no error occurred; so if no errors occurred, OK, I am going to output HTML, as normal.1425

But which HTML am I going to output? Am I going to output the shipping and billing address form to request the shipping and billing information?1432

Or am I going to output the Thank You message?1440

So, if action equals checkout, then you output the shipping and billing information form.1444

If action equals completeOrder, which means it is completing the order and going to the thankYou page, you are going to output the Thank You message.1451

And down here, you can see that, if neither of these occur, we are going to output an error message,1460

stating that a correct action wasn't provided, or that the Shopping Cart was entered, but it didn't have at least one item in it,1465

or that not all of the necessary shipping information was provided.1477

One thing to note is that, in our earlier version of checkout.php, in our form that contained the table with text fields1483

for our shipping and billing information, we had the form action set to thankYou.php, so it forwarded all of that data to thankYou.php.1499

Well, thankYou.php doesn't exist anymore, so we are going to change that value to itself, to checkout.php.1507

So, if we look at checkout.php, and we look at the HTML Output section for that, we can see that we have changed that to checkout.php.1515

Now, one other change that we have also made is: because the checkout.php form now has an action variable1523

that gets passed to it, when we submit data from the viewCart.php form, 1529

we also have to submit an action variable that says what action I am completing.1536

From the viewCart, it is going to be checkout; so if we go and look at viewCart.php in our version 8.1,1540

here is the form that outputs all of the item information.1551

If we look at the very bottom, by the Submit button, we have added a hidden field.1555

What that is going to do is pass an action to the checkout page, and it is going to say, "Tell the checkout.php to perform the action checkout."1561

And so, that is how the viewCart communicates to checkout.php what to do.1570

For a homework challenge, as usual, I just want to make sure you understand the different things that we have done in this code.1580

It has definitely gotten a lot more complicated, as we have added a lot more control structures, and especially nested control structures.1586

So, you are going to want to take a look at the code and make sure you are understanding how the flow of the code works--1593

essentially, how now we have input validation that nests everything one level deeper than before,1600

because before we were just validating that GET data was provided; now we are validating that the GET data is valid.1609

So, that gives us two nested if statements and the chance for two different errors,1617

one error being "You have reached this page in error," because no GET data was provided, or 2) the GET data you provided was invalid.1622

So, one of the things I want to make sure you understand is this empty construct we have introduced.1630

We will be using that a bunch, because it is used to process form data and make sure that form data was provided as needed.1633

And then, also, just review the concept of sending an action variable to a script, 1641

in order to get that script to conditionally execute sections of the code.1648

As you can see, in our checkout.php today, the action variable determined 1) what sort of data processing occurred 1652

at the top of the script, meaning whether you were processing the data for a checkout, which would be calculating the Shopping Cart total,1660

or whether you were validating that all of the appropriate shipping information was provided.1668

And then, also, we used that to conditionally output the proper HTML.1674

So, if it is a checkout, we are going to output the shipping and billing form.1680

And then, if it is completing the order, we are going to output the thankYou message.1686

That conditionally outputs the HTML.1691

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1695

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

Today's lesson is going to be a rather fun lesson, because we are going to be learning about how to use PHP's built-in mail function,0004

which is going to allow us to send emails from our PHP scripts.0010

Specifically, we are going to talk a little bit about the built-in extension.0016

And then, we are going to go over some basics of SMTP, which stands for Simple Mail Transfer Protocol.0021

And what that is: that is how email messages get transferred from a sender to a recipient on the Internet.0028

So, we are going to talk a little bit about that, and we are going to talk about how it works in both Windows and in a Linux or UNIX operating environment.0034

We are going to talk about some mail configuration directives that are within php.ini.0042

We are going to go over a little bit about mail server authentication.0049

And then, talk about a program provided by XAMPP called fake sendMail for Windows,0053

which allows you to send email from your PHP programs with a little bit more flexibility than comes built into PHP by itself.0059

And specifically, we are going to talk about the function that does it all, which is the mail function,0070

which is the built-in function of PHP that allows you to send email.0075

And then, we are going to update our web application to include a contactUs page that is going to allow a customer to email the store administrator.0078

As mentioned, PHP provides a built-in mail extension, and what it does is: it provides two functions, but the main function that is used is this function here, mail.0090

What that allows you to do is send emails from your PHP scripts.0103

Now, in order to use the mail function from your scripts, there are several configuration directives that you will need to set up in php.ini.0107

And we are going to walk through that, but before we do that, I am going to go and give a little bit of overview about how email on the Internet works.0118

SMTP, or as it is known, Simple Mail Transfer Protocol, is the protocol that is used between servers on the Internet to exchange email.0126

When you send an email from one email address to another, 0138

SMTP is the rules that are used to get that email from where it originated to where it's going.0142

The protocol is implemented by things known as mail transfer agents, or MTA's,0150

Or, as they are more commonly known, and you have probably heard them referred to as, a mail server.0156

And whenever you send an email from an email client like Outlook or via a web-based email like Gmail,0161

your message gets sent along to a mail server, an SMTP server, as it is sometimes referred to,0169

which will relay it (pass the message along) to the recipient's receiving mail server.0176

Now, I just want to go over how this works in Windows, because there is a little bit of difference between0190

how email is sent, typically, in Windows, and in a Linux and UNIX operating system.0194

We have a diagram here, and we have a client computer, and this little symbol is for the Thunderbird email client.0201

It is free from Mozilla, and it is an email client used to send and receive emails.0214

What happens is: when you are in Thunderbird on your computer, your Thunderbird application--when you go to send an email,0219

it contacts a mail server, typically on your local network, and it sends a message to it by SMTP.0227

What happens is: once the mail server receives that message, it reads it and figures out where it needs to go.0237

And it sends it through the Internet over to whoever the recipient is, whatever domain they reside on.0244

It is going to send it to their mail server, and it is going to use SMTP to do that.0252

And then, what happens is: when the client on the other side, the recipient, opens up their Thunderbird client0257

(let's say they are using Thunderbird as well) to download their email, typically what happens is: they will download their email0264

from the mail server, using what you might have heard of as the POP or IMAP protocols.0269

We are not really going to be talking about that too much in this lesson.0278

We are going to be concerned with the sending of email, so we are going to talk about the SMTP structure.0280

So, in Windows, this is typically how it works: you have an email being sent from your client, and it is sent to a mail server,0285

which sends it out over the Internet; and the mail server is typically on your local network.0292

Now, the typical setup in a Linux or UNIX environment is a little bit different.0299

In this case, we have as our client PHP; and an email client typically refers to something that sends or receives email.0304

And because we are going to be sending email from PHP, we can consider PHP a client.0311

Now, if you notice, there is no mail server over here, like there was in the setup.0317

On a typical Linux setup, there is a program called sendmail, which you may have heard of before, which is its own mail server.0322

So, typically, we already have PHP running; it has sendmail running on the same computer.0334

So, instead of forwarding a message by SMTP out to a local mail server, who will then forward it along to the client,0339

like this, what happens is: PHP or your mail client (you can do Thunderbird, as well) will send the message along to the local sendmail program running.0349

And then, what sendmail does is: that is the actual mail server, and it is the one that goes out through the Internet 0361

and, via SMTP, sends it along to the client's mail server.0368

And then, same as before, the recipient can download it by a POP or IMAP to read the email.0373

The main difference here is that typically, on Linux, you have your SMTP server running on the same computer as your email client.0381

Now, as mentioned, php.ini provides a number of configuration directives that allow you to configure how the mail function is going to work.0396

And the way you set the configuration directives depends on whether you are going to be in a Windows environment or in a Linux or UNIX environment.0406

Typically, when you are using a Windows environment, you are going to be setting a directive called SMTP.0416

What that does is: that allows you to specify the name of your local email server that you are going to use to send out your messages.0422

In our diagram, that was that first server, where the client passed the email along to be sent out over the Internet.0432

In Linux environment, you are going to be using, typically, the directive sendmail_path.0439

What that does is: that gets set to the location of where the sendmail program is on your local machine,0443

because, as we said, sendmail runs on the same machine as your email client or PHP.0451

With the sendmail_path, we actually specify the file location of that sendmail program or sendmail binary.0457

And that way, PHP knows how to invoke the sendmail program to get it to send the email out over the Internet.0463

If we go and take a look...if we open up php.ini, quite a ways down the page, 0469

in the section where extensions are configured, there is a section called Mail Function.0477

You can see a couple of directives here: here is the SMTP directive that we talked about; and this, as mentioned, says "For Win32 only."0485

This is typically what is used in the Windows environment.0494

What you would do is set it to your local SMTP server, and that is going to depend on what you use for your email.0497

For a lot of people, if you have, for example, cable Internet or DSL, your cable Internet provider or ISP0507

gives you the name of a server you can use as an SMTP server, which allows you to send email.0517

For example, sometimes Road Runner is like a Time Warner cable Internet service.0522

Often, their SMTP server that they give to you is called something like smtp-server.roadrunner.com.0531

And so, what that does is...what this directive is saying is: that is telling PHP that, when it sends an email using the mail function,0541

that it is supposed to send the email to this SMTP server on your local network,0553

and then, to have that SMTP server actually send it out over the Internet.0561

We will set this back to its default value.0567

Now, the other directive we talked about was the sendmail_path; and this, as you can see, says "for UNIX and Linux."0573

What that is: if you look further down, it is basically a path to the sendmail binary, which is a sendmail program that runs on your computer.0580

Now, this is a Windows path, because we are running a Windows server.0593

We are going to talk in a little bit about a sendmail program that is provided by XAMPP, so that you can mimic the sendmail program in Linux.0598

But typically, this is going to be set to a UNIX path, and it is going to be set to wherever your sendmail binary is located at.0606

Let me just go ahead and comment this back out and save.0615

One of the things that often happens is: your outgoing mail server, your SMTP server, often requires authentication.0623

And that is because, if it didn't require authentication, it is considered an open relay, they call it.0633

Spammers would take advantage of it and just send email requests to it, and they could use that server to send out email 0640

as much as they wanted to, to different places.0646

So, typically, your SMTP server, like the one provided by your local cable provider,0649

is going to require some sort of authentication, so it knows that you are allowed to send emails from that server.0656

It can be done in a couple of different ways.0662

One common thing is to use a username and password that your ISP provider will give you.0664

Another thing that can be used in combination with the username and password, or on its own, is: your ISP will require that0672

any emails sent using their SMTP server, their local outgoing mail server, be originated from a computer that is on the same local network as the mail server.0681

So, for example, if you have a cable Internet service, you have to be logged onto your computer at home,0693

that is accessing the Internet through your cable modem, in order to use, for example, your local SMTP server.0702

If you try to access it elsewhere, it may not authenticate you.0708

In a Windows environment, we can use the smtp directive; and the Windows environment is what we are developing in, in this course.0714

And if that doesn't work, because authentication is required (a username and password is required), there is a program0721

that I mentioned, called fake sendmail for Windows, that is provided with XAMPP.0730

What it does is: it gives you a few more options for being able to connect to your local SMTP server, allowing you to provide authentication.0736

As mentioned, the program is called fake sendmail for Windows, and it is located in...there is a directory in your XAMPP installation0750

called sendmail, and that contains...it is called sendmail.exe, which is this program here.0760

And the feature that it adds onto the base functionality that PHP provides through php.ini, which just lets you provide0768

a basic SMTP server through the smtp directive, and doesn't allow for any authentication...fake sendmail has an add-on feature0777

that allows you to be able to specify a username and password to your SMTP server, so that, for those of you whose ISP's require you0788

to do authentication before sending an email--it is going to give you the ability to do that.0799

The username and password that you provide to your SMTP server gets configured in a file called sendmail.ini,0805

which is in the sendmail directory of the XAMPP installation.0816

That configuration file is how you specify to this fake sendmail program how you are supposed to connect to your SMTP server.0819

What that does is: you specify the name of the server (for example, smtp.roadrunner.com or .net).0829

And then, you provide your username and password your ISP provider is giving you, in order to authenticate yourself to that server.0836

Let's take a look at how this fake sendmail program changes things when we are working with XAMPP for Windows.0848

As you can see, in this diagram, we have our mail server back, and then we also have fake sendmail in the diagram, as well.0858

And so, the way using the fake sendmail program works is kind of a hybrid approach to sending email in a Windows environment.0867

You have your email client (in this case, PHP), and instead of sending an email directly to the mail server 0875

by the smtp configuration directive in php.ini, it sends it to a fake sendmail program.0884

It is configured with the sendmail_path; so even though we are not using the UNIX computer, we configure the sendmail_path directive.0892

And as we saw in the php.ini file, XAMPP goes ahead and, when you have configured XAMPP...it set the sendmail_path directive0899

for you to point to this fake sendmail program.0911

And what you do is: you turn that directive on, and so when PHP goes to send a message, it sends a message to the fake sendmail.0913

And then, what sendmail does--it is not an actual SMTP server; it is not an outgoing mail server, like the real sendmail is--what it does is:0924

it goes ahead and still uses the local outgoing mail server on your network.0936

But what it does is: it allows you to configure it, so that it can provide a username and password, so it can authenticate.0942

It sends it out to your mail server by SMTP, using authentication.0950

And then, everything goes as normal from there; your local mail server sends it by SMTP 0967

through the Internet, over to your recipient client on the other side.0975

If we go and take a look at the sendmail.ini file, which is the fake sendmail configuration file, we can see, it has a number of directives in it.0980

It is formatted very similar to php.ini.0991

The main directive you are going to use is smtp_server, which corresponds to the smtp directive in php.ini.0995

That is going to be the name of your ISP's outgoing mail server; so again, it could be like smtp.roadrunner.com.1003

And then, it has a couple of other configuration directives that you can do.1015

You can set (and this is going to be helpful--we are going to use this when we show an example of sending an email) error logs1020

and debug logs, and they provide you information, if you are having trouble configuring the sendmail.exe, the fake sendmail, to work.1031

That is going to be useful to you, if you are having problems.1039

Then down here (and this is sort of the key difference), there is an auth_username and an auth_password directive,1042

which is going to allow you to enter whatever username and password your ISP provided to you to use to authenticate yourself to the SMTP server.1048

So, for example, the username could be your email address; you could say, "My email address is user@roadrunner.com,1062

and my password is" I wouldn't do something like this, but it would be "password."1067

And so, that is going to configure sendmail, so that when PHP goes ahead and tries to send an email,1073

it is going to run this fake sendmail program, which is going to read this sendmail.ini configuration file.1081

It is going to be able to gather your username and password to authenticate itself to your local SMTP server, 1087

specified up here, and then send the email that way.1096

Let me just go ahead and put these back.1100

So now, let's talk about the mail function, which is the function built into PHP that allows you to send email.1121

It is what gets configured through php.ini, as we had talked about.1127

It has three required arguments: you have to have a to email address; you have to provide a subject; and you have to provide a message.1133

It also has two optional arguments, and it also returns a boolean value 1141

indicating whether the email was successfully passed on to the mail server for delivery.1149

We are going to talk a little more about that, because, just because the mail function returns true, 1155

indicating that your email message was delivered to the mail server, it doesn't necessarily mean the email is going to be properly delivered.1160

There may be problems on the mail server, such as if you have an incorrect email address or something like that.1168

So, you have to kind of be careful of that; we are going to talk about some different cases where the mail function1174

will return true, even though your email doesn't actually get sent.1181

Now, one important thing to note is that the first optional argument, which, if you look at the PHP documentation for mail--1185

the mail function--is called additional_headers, and it is an optional argument, but it is typically almost always required.1193

And what the argument is, is a string where you can pass email headers, like From, CC, BCC, and so forth.1202

Now, in order to send an email, you have to have a from email address specified.1213

So, even though there is no from argument in mail, what you have to do is specify a from header--1218

create a string that contains a from header that has the form right here--it has From: and then the email address you are sending it from.1228

You have to create that as a string, and add that as a fourth argument to the mail function.1237

An example of using the mail function: we have your to email address as the first argument.1242

You have some sample subject text; you have the content of your email message.1248

And then, this optional, but pretty much required, parameter is the additional_headers parameter.1254

And here we have provided the header From: and we provided a from email address.1263

Let's go and take a look at one of our scripts that we have created to show this.1269

First of all, let's look at mail.php, which is a script we have created to demonstrate just the basic mail functionality.1277

What we have done is: we have hard-coded a couple of different values.1288

We have hard-coded a to email address, a subject, and a test message.1291

We have also created email headers, which holds this required From: header that has the from email address.1297

And then, we make a call to the mail function, including the to email address, the subject, the message, and then this email header.1308

And then, what happens is: we output a message saying whether the email was sent successfully, or there was an error.1317

What happens is: when we run the mail function, as mentioned, it returns a boolean value that gets stored in the variable sent.1323

And so, we can test sent down here: if it's true, the email was sent successfully; if not, there was an error.1329

But as mentioned before, it doesn't necessarily mean the email is actually going to be delivered.1335

It just means it was successfully passed along to the mail server.1338

If we go and try to run this page, everything is hard-coded; it is just going to go ahead and try and send out an email.1343

And if we go ahead and load the page, you can see, we get an error.1349

And it is saying "failed to connect to mail server at localhost; verify your "SMTP" and "smtp_port" configuration directives in php.ini are set properly."1356

And we also get our own error message.1366

That is saying that our mail is not configured properly, so what we are going to do now is go ahead and walk through the process1369

of configuring php.ini and sendmail.ini, so that we can send emails from our PHP scripts.1376

Now, we are going to be using the fake sendmail program, because the mail server that we use at Educator.com requires SMTP authentication.1385

And so, using sendmail is going to allow us to provide a username and password to authenticate ourselves.1395

If we go to php.ini, we are going to comment out the smtp directive, because we are not going to be having PHP try and connect to the local SMTP server.1400

We are going to have it use the fake sendmail program.1414

So, we uncomment this sendmail_path directive, which, when you set up XAMPP, is automatically configured to point to the fake sendmail program.1416

And then, if we go into our sendmail.ini folder, we are going to enter the SMTP server we use at Educator.com, which is called mail.educator.com.1428

We are going to go ahead and turn on the error log file and the debug log file, because those will be useful to us in a bit.1444

And then, we are going to go ahead and enter our SMTP username and password that we need for authentication.1451

Now, the username we use is test@educator.com; that is our email address.1457

And then, our password...I am going to do it off the screen here...is what we need to authenticate with.1464

Now, because we have changed our php.ini file, we need to restart Apache, as we always do any time we make changes.1478

So, I'm going to stop it and restart it.1489

And if we go and reload the page, we should see that our email was sent successfully.1493

What happened is: this time, when we ran it, when we called the mail function, PHP looked at the php.ini configuration file.1506

It saw that we are using a sendmail binary to send our email to the local SMTP server, and then it went ahead and invoked that.1514

It read the sendmail.ini configuration file to get our username and password to be able to send it to the server.1527

So, if we go and look at our local instance of Mozilla, the Mozilla email client is running, and we can see that we just received the email from our web page.1533

It says mail function test; and I'll just turn the headers off.1547

And so, it confirms that our email function has worked.1553

One thing to note is: if we go back to our mail page, typically, you actually prepend the mail function with the error control operator,1562

because if an error gets generated, you get this sort of ugly warning message, as we had seen earlier.1575

I'm going to go ahead and do that here, and then we're going to create an error message that is going to get 1583

this PHP errorMsg variable that we talked about when we learned about the error control operator.1591

And then, if we have an error, it is going to output it down here.1598

And so, just to show how that works, I am going to go back to our php.ini file, and just temporarily get rid of the sendmail.1601

I'll just use localhost.com and make up some SMTP server that shouldn't work.1621

If we restart our Apache, and we reload the page...it's taking a little while, and that is probably because we have messed up the configuration.1627

You can see that we have gone ahead and seen that there was an error sending the email.1658

But we didn't get that ugly warning message, because we used the error suppression operator.1665

We'll go back and look at mail.php; we can see how that worked.1670

One other example page that we have created is called emailForm.php.1683

What this is: it is sort of an expansion on what we have just learned; it is a way to...instead of hard-coding an email into our system, 1690

it's going to allow us to specify an email address, a subject, and a message, and actually send the email out.1699

And before I do that, let me go ahead and correct the configuration again on php.ini and restart the mail server.1706

And I am going to go ahead and run that mail.php page again, to confirm that our email functionality is working again.1719

"Email was sent successfully," and if I go and look at my inbox, I can see that it was sent; so, the email is back, working again.1731

The way the email form works is: you enter a return address email, or a "from" email (and this is something a customer could do on your website).1739

I'm just going to create a test subject, test email comments...1749

And if we click Send Email, it is going to be using the same process,1759

except it is going to be using the data we provided here, to go ahead and send the email.1763

If I go and look at my inbox, we can see an email created; it has Test subject as the subject, which is what I provided.1767

And it has From: test@educator.com, which is what I provided in the form, and then also the comments that I provided in the message part of the form.1779

So, if we go and look at emailForm.php, when we take a look at it, it takes two GET variables.1790

It has an action variable, and then it also has a contactInfo variable.1800

And what happens is: when you go to that page originally, no action variable is provided, and so what it does is: it loads the form that we saw.1804

The form has three different fields in it that all populate a contactInfo associative array.1814

Here, they populate it with the keys from, subject, and message.1820

And then, when we submit the form, we go ahead and submit it with the hidden field, called action, that says send email.1825

And the form, if you notice, submits to itself, emailForm.php.1831

So, when the form reloads, it is going to come down here and test to see what HTML output...1837

It is going to say, "If action is null, or if action is not equal to sendmail, output the form."1842

Well, because the action is going to be set to sendEmail now, it is going to go down here, 1847

and it is going to process the information that we submitted, and send out the email.1851

As you can see, we have hard-coded the to email address, because we want to send it to the admin, for example, on this website,1857

which is just going to be our test@educator.com email address we have set up.1865

And then, it pulls the from, subject, and email message from the contactInfo variable that was provided by a GET.1869

We go ahead and add the From: header, which is necessary to send the email.1876

And then, go ahead and run the mail function, and use the error suppression operator so we don't get an ugly warning message.1880

And then, we output an error message if an error occurred, and if not, we output that the email was done successfully.1887

And as we saw when we submitted the form, it is currently working; and so, everything works as expected.1894

So now, we are going to talk about updating the web application.1905

Now that we have learned about how to configure email to work in our PHP setup, 1907

and we have learned about how to use the mail function, we are going to add...1912

we are going to call it a contactUs page...to our web store application.1916

What that is going to do is: that is going to allow a customer to go ahead and send some comments to the store administrator by email,1921

saying maybe they like this or that about the store.1929

It is an example of a way, if you were to have your own website, you could have people submit information or comments to you.1931

It is going to make use of the mail function, and we are going to make use of some email-related constants that we are going to add to config.php.1938

We are going to be creating contactUs.php; we are going to be editing the config file, 1948

because we are going to be adding some constants, which you will see in a minute.1954

We are also going to edit the footer, and that is because 1956

we are going to add a link to the contactUs page at the bottom of all of our pages.1959

And then, we are not going to talk about it, but there are some modifications that are going to occur to store.css that format the contactUs form.1964

Really quickly, to talk about the new page, contactUs.php: similar to the example we have just gone over, 1973

it is going to take two GET input parameters: one is going to be called action, and one is going to be called contactInfo.1980

And action, as before, is going to determine whether the page is just going to show the form to the user1988

that allows them to enter their comments, or whether it is actually going to 1992

process the comments that they submitted by a GET and actually send out the email.1995

What we are going to do is: we are going to use the value contactUs; 2002

we are going to set the value action equal to contactUs when we want it to process the email.2005

So, when we have a user submit the form, we are going to submit the hidden input field, as well, that is called action.2010

And it is going to be set to the value contactUs, so that when the page reloads, it is going to know that, 2016

instead of outputting the form, it is supposed to go ahead and try and send the email.2023

contactInfo is an associative array that contains the information the customer submits on the Contact Us form.2028

It is going to contain their name, their email address, and whatever comments they submitted.2036

And we are also going to have it so that the form validates contactInfo, just to make sure that all three of these fields...2044

We are going to require that all three of these fields be provided.2051

And just so you know, the default action for the page is just to display the Contact Us form.2055

That is if no action is specified to the form, or you specify an action that isn't the value contactUs.2060

The default action is to always just go ahead and display the Contact Us form.2067

Let's go take a look at what the form looks like.2071

If we look at the web application--this is the new version, 9.0, we can look at...2075

Well, first, let's go to store.php; and we can see, there has been a link added to the bottom of all the pages, 2080

because we just added a link to footer.html.2087

And if we go and take a quick look at that, you can see, we just added one more link to the bottom here.2091

And when we click on that Contact Us link, it is going to take us to contactUs.php.2099

This is what the form looks like: it has a place where a customer can enter their name, their email address, and their comments.2103

And so, I'll go ahead and enter my name, my email address, and then some comments about the store.2110

And click on the Contact Us button; it is going to go ahead and send an email to a preconfigured address, which we have set up in config.php.2126

So, the email was sent successfully; it says "Thank you for your comments."2139

Actually, since I have my email client running, we can go in and look at it; and because the preconfigured email that it gets sent to 2142

is our test@educator.com email, we can see that it sent an email, and it said "Matthew Machaj had some comments for the store."2148

And then, it output my comments that I had submitted on the form.2156

Let's go and take a look at the code that does this.2160

First of all, let's take a look at config.php; and in config.php, we have gone ahead and added two constants.2164

We have added one called ADMIN_EMAIL_TO, and what that is: any time a user submits comments on the Contact Us form,2173

it is going to get sent to this email address; because we always want it sent to the same spot, we set it up as a constant.2183

And in this case, we are calling it ADMIN_EMAIL_TO.2188

Additionally, we always want our administrator, when they look up their comments received from the store in their email client--2192

we want to have the same subject line, so that they can identify where they are coming from.2200

And so, we have created a constant for that called CONTACT_US_EMAIL_SUBJECT.2205

It just says "Educator Store comments," which lets the administrator know that somebody submitted comments from the Educator store.2210

Now, the contactUs.php page--at the top, it processes the two GET variables that it can use.2218

One is action, and one is contactInfo, as we had talked about.2229

And then, in the data processing section, if the action is set to contactUs, which means the user submitted the form,2234

it goes ahead and just checks to make sure all of the fields on the form were not empty.2240

And if so, it goes ahead and will output the appropriate page title;2246

if not, it's going to output an error message saying "You must complete all fields to use this form."2250

So, for example, if we go back, and we leave out comments, it is going to give you the error message, 2255

saying, "You need to complete all the fields on the form."2265

This is error processing, as we had seen before.2271

And then, on the output section, we output a common title, so the page is always going to say Contact Us.2274

If no error has occurred, and the action has not been specified, or it is not equal to contactUs,2279

then we are saying, "OK, go ahead and output the Contact Us email form," and the Contact Us form submits its GET data to itself.2286

It uses the contactInfo associative array, and then, it also defines, as a hidden GET variable, action with contactUs.2295

So, when the form is submitted, you will know how to process the contactUs information.2307

Also know that it is not supposed to output the form, but in this part down here, it is actually going to say,2312

if the action equals contactUs, it is going to go ahead and send the email.2318

And in this case, we can see, we created some short variables for the customer's name, the email, the comments they submitted...2323

which loads information from the contactUs GET variable.2330

What it does is: we then go ahead and build up an email message, which you saw in the email program we had.2336

And what it does is set it up so that it outputs the person's name.2342

It said, "So-and-so had some comments on the store," and then we add to that this email message, the comments that were provided.2345

And by default, it is going to send the email in plain text; so here, we are using new lines, as opposed to breaks, to format the email how we want.2356

We create the email header, and in this case, instead of having it hard-coded, 2365

we use the email address provided by the customer and set the header that way.2370

And then, here, we go ahead and call the mail function.2376

And as you can see, we have used the two constants we created in config.php.2379

For the to address, we have set it equal to the ADMIN_EMAIL_TO constant, so it is always going to send it to our administrator email account.2383

It is always going to have the subject specified by the CONTACT_US_EMAIL_SUBJECT constant.2390

Here, we have included the message that we built up, up here, which has the customer's name and their comments.2397

And then, we have also added the email headers variable, which has the From: header for the email message.2402

Down here, if this is successful (and here we use the error suppression operator again), it outputs a Thank You message.2410

If not, it says "There was an error in sending your comments."2417

And so, that is how the Contact Us page works.2422

One thing you might note is that (and this is kind of related, but it's a commenting thing) is: sometimes, you will see that,2424

at the end of if statements, for example, we have if action equals null, or action is not equal to contactUs,2433

when you are getting ready to enter another elseif statement, you can add a comment to the end, 2440

on the same line as the curly brace of the if statement, saying the test condition that was used to enter that.2446

So, down here, we know that the section up here was entered if action was equal to null or if action was not equal to contactUs.2452

Similarly, at the bottom of this elseif statement, we can, at the end of the code, add a comment saying,2460

"OK, this section was entered from action=contactUs."2467

That is just a way to provide some feedback to you, as far as comments go, within your script, to make it a little bit easier to read,2469

because when you have long elseif and if statements, like this, you might not know exactly what the test condition was2477

that had you enter that; and so, this just adds a little more information to that.2485

So now, I just want to quickly talk about the homework challenge we are going to have for this course.2494

I would like you to go ahead and try and set up your XAMPP configuration, so that you can send email from your PHP scripts.2497

And you may just be able to edit the php.ini file; just edit that smtp directive.2504

Maybe your local SMTP server doesn't require authentication, or it does require authentication, but it doesn't require using your password;2510

it just requires that you send the email from a computer on your network.2517

So, I would suggest going ahead and trying just setting that first.2522

You will need to contact your ISP to find out what the domain name of your SMTP or outgoing mail server is.2525

Alternatively, you may have to use the fake sendmail program, if your outgoing or SMTP mail server requires authentication.2532

And what you can do there is: as we had gone over, you can edit sendmail.ini 2541

in order to add your username and password, so that you can perform authentication.2546

You also are going to need to change, in php.ini (not to forget)--you need to enable the sendmail_path directive,2551

which is going to tell PHP to use the fake sendmail program.2558

Once you have done that, just go ahead and set up a sample script that is going to call the mail function with some hard-coded values,2562

making sure to include the From: header as that fourth argument to the mail function.2569

And just do that in order to test the configuration; go ahead and try sending an email, 2574

and then make sure that you can see it in your email client, that it is actually being sent, just to verify the configuration.2578

Once you have done that, just create a script, similar to what we did in the course today,2587

that contains a form where a user can put their email address, a subject, and a message.2592

And, using an action GET parameter, have the script submit the form to itself;2597

and based on the action that says something like contactUs or sendEmail, 2604

have the email be generated, using the information that the user provided in the form, and have it send out the email.2609

Be sure to test to verify that the mail function worked and was successful.2616

And then, also check in your email client to make sure that the email was delivered.2621

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.2625

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

Today's lesson is an extremely exciting lesson--probably my favorite of the whole course--0004

because we are going to be teaching you how to create your own user-defined functions,0009

which is really going to increase your efficiency as a PHP programmer.0012

Specifically, we are going to talk about how to define your own functions, and the syntax that is involved with that.0018

We are going to talk about function parameters, which is ways to pass data to functions.0024

We have previously talked about that when calling functions using function arguments.0029

We are going to talk about return statements, which allow you to return a value from a function,0033

because, as we had learned before, functions are expressions, and they have values.0037

We are going to discuss where to define functions within your PHP code, 0043

and that is going to involve a discussion of the include_once construct, 0047

which is an extension of the include construct that we have talked about before.0052

And we are going to also talk about some reasons why you use functions, and why to separate code out into functions.0056

Then, we are going to make an update to our web application, version 10.0, 0063

where we are going to extract some of the code from it and put it into functions, 0068

so we can see our user-defined functions working firsthand in our web application.0073

And then, we are just going to quickly talk about when you do output HTML in functions, and then also coding conventions as it relates to functions.0079

Defining a function requires four parts: it requires the function keyword (and this is an example of a function declaration);0091

you provide a function identifier or a name of the function; then, in parentheses, you provide what is known as a parameter list0100

(we are going to talk more about that in a minute), and then, just like a control structure, 0108

you have a statement group enclosed in parentheses, and that contains all of the code that gets executed when a function is called.0112

And this section of a function is known as the function body--the code contained in the function is known as the function body.0120

Anything contained, any PHP code that we have gone over so far, is allowed anywhere else in PHP script.0127

One thing to mention is that function identifiers or function names follow the same naming rules as we have for variables and constant identifiers.0135

Let's take a look at some examples of some basic functions, and see how they work.0146

Here, we have a sample script called functionExamples.php, and right here, this function is an example of the most simple function.0153

It is a function that, when it gets called, does nothing.0164

It has no statements in it, which is a perfectly legal function.0167

Now, as we know, when we call a function, it stops execution of the current script, goes and executes the code in the function,0170

and then returns the value to the script where it was called from; and then, the script continues to execute.0178

So here, in this case, we have defined this function; and then, I am going to go ahead and just call it.0183

And the way we do that is: just as we have been calling built-in PHP functions, we have the function name with the parentheses and a semicolon.0191

And this function does nothing, but it shouldn't cause any problems or any errors, and when we load the page, nothing should happen.0200

But this is just to demonstrate that a function can contain anything, including the lack of any code.0206

If we load functionExamples.php, nothing happens.0215

The other thing we can do is: we can create a function that just has one statement in it, but it is an empty statement.0220

And again, this is just to emphasize the fact that functions contain statements, and they contain any types of statements, including an empty statement.0233

And if we go ahead and call this function, we should receive no output, as well.0243

I'll go ahead and load the page, and nothing happens.0249

So now, we are going to get a little more interesting: we are going to have our function do something.0254

We are going to create an example function that is going to output some code by an echo statement.0259

So, we have this function called example1_2, and all we are going to do is simply echo a statement that says "inside example," and then the function name.0269

So, when we go ahead down here, below the function, and we call this function, example1_2,0284

what is going to happen is: when we reach this statement right here, it is going to call the example1_2 function.0297

It is going to run the code inside of it, which in this case is just an echo statement, 0303

and it is going to echo that statement, and then continue processing the rest of the script.0306

So, we should see this line output now, when we run the script.0310

And when we reload the page, you can see, the echo statement was output that we had in the function.0316

So now, I want to talk about something called function parameters.0330

Function parameters are variables that are defined when you define a function, and they are variables that can be used within the function body.0335

They are described in between the parentheses of a function definition; and you can have as many parameters as you need.0344

When you call a function, as we have seen with built-in functions to PHP, we can supply data to functions.0351

And those are called function arguments; the data you supply is called an argument, and the argument fills the parameter variables of the function.0359

For example, when we define this function with param, we define it as having one parameter called param.0369

And what that means is that we can access this variable, param, anywhere within the function body.0377

And here, we can see that we just echo the value of param.0383

And the way that that gets said is by...when you call the function with param, you provide a function argument.0385

And what happens is: param gets set to this value.0394

So, every time this function is called, whatever value is supplied as an argument to the function--this parameter will get set to that value.0402

Now, I use the term parameter and argument, and it's sort of a technical distinction.0413

Technically, when you define a function, and you create (I'm erasing this) a parameter list, the variables that you make available0416

in the function definition are known as function parameters.0431

And when you call a function, you call a function with arguments, and those are the values that the parameters are going to get set to.0437

And sometimes, you will hear those terms used interchangeably; but essentially, they refer to kind of the same thing.0443

When you call a function, you supply arguments which set the value of the parameters specified in the function definition.0448

And you can have multiple parameters in a function, and what happens is: let's say, for example, there was another parameter here--0456

the way that it would get set (let's call it param1) is: when we call the function, we would supply a second function argument.0469

The order that the functions are supplied in specifies the order that the parameters get set in.0482

So, the first parameter gets set to the value of the first argument; the second parameter gets set to the value of the second argument.0494

Let's go take a look at some functions that use parameters.0502

So here, we have another example function that we are going to create that is going to take one parameter.0513

And all that it is going to do is echo the parameter that gets passed in.0518

For example, when we call this function, it requires one parameter, so we are going to have to supply it a value that it can output.0526

So, we are going to supply it with a string; and when we call the function...let's supply it with the string "Hello, World!" for example...0533

Now, what is going to happen is: when we call this function, this code is going to stop executing right here.0548

It is going to go up to where the function is defined; it is going to set the parameter variable, 0554

this param variable, to the argument specified, which was "Hello, World!"0560

And then, it is going to run the code in the function body, which just says to output the parameter variable, 0565

which is the string value that was passed in.0571

So, when we run our code, we should see it output this string "Hello, World!"0574

And if we go and take a look at that (oops, I had a typo; I forgot an e down here), you can see that it output "Hello, World!"0580

And if we include a break statement up here, this will look nicer...or actually, let's just get rid of this function call.0601

We can see that "Hello, World!" is output.0618

And the unique thing about function parameters is: they can be set to a different value every time the function gets called.0622

And that is what makes the function useful: it allows you to dynamically do things.0629

It can do one thing in one instance...for example, output one string one time it is called, 0632

and then output another string when it is called a different time.0637

So, for example, we could input to this function the string "Goodbye" and then now, when we call this same function again,0640

even though it is the same function, it is going to perform a slightly different action, based on the arguments that we specified.0651

So, when we load it now, it is going to output this new string statement that we passed in.0660

Let me go ahead and comment out this line.0669

And now, what we are going to do is demonstrate, using a function that has multiple defined parameters.0672

Here we have a function with two parameters called param1 and param2.0679

What I am going to have it do is create a string that is just the concatenation of both parameters.0684

So, these parameters are both going to be strings that get passed in, and then we are going to create a string inside the function0691

that is just going to be the concatenation of those two strings, using the dot operator.0699

And we are just going to echo this concatenated string.0708

When we call this function, example2_1, we provide it with two parameters.0718

In this case, we provide it with "Hello," and then, as a second parameter, we provide it with the string " World!"0725

So now, when we call this function--when we execute this function call--it is going to take these two strings.0741

It is going to set the value of param1 in this function to Hello,; it is going to set the value of param2 equal to World!.0747

And then, the function is going to execute, and it is going to execute the concatenation of those two strings.0753

We should, again, see the string "Hello, World!" output.0761

If we go and reload the script, we can see, "Hello, World!" was output.0764

As we know from our Introduction to Functions lesson, functions are expressions.0775

What that means, that we know about expressions, is: they have a value.0780

So, functions always have a value, and they always return a value to the script that they were called from.0783

And the value of a function is known as its return value, and return values in PHP can be any type.0790

It can be an array; it can be a scalar, as we learned; it can be an object.0801

The way that you specify the return value of a function, or the value that it returns to the script it was called from, is using a return statement.0807

One thing to note, that we are going to show an example of in a second, is that you can have multiple return statements within the same function.0817

What happens is: when a function is executing, any time it reaches a return statement, 0824

it automatically ends execution of the function and returns whatever value it was set to return in the return statement.0830

And even if there are statements that are still unexecuted in the function, it doesn't matter.0839

Once that return statement is reached, the function ends, and it returns back to the execution of the current script.0842

One other thing to note is that, if a return statement never occurs, or is never executed, within a function,0848

null is the value returned by default for all functions.0855

Let's go take a look at the return statement in action.0859

The first thing we are going to do is: we are going to have the return value...0870

we are going to use a return statement that is just going to return a static value.0873

So, it's going to have it return the string "Goodbye," and then we'll call the function, and this is a function with no parameters.0877

What is going to happen when we call this function in this statement right here: example3_0 is going to get called,0898

and what it is going to do is: it is going to execute the function body of example3_0.0907

And we see in the function body that all it contains is a return statement.0912

So, what this is going to do is: when this function reaches this return statement, 0914

which is the only statement in the function, it is going to return the value Goodbye.0918

And that is how the return statement works: the statement starts with the return keyword, followed by a space, 0923

and then whatever value you are going to return, which could be an expression; 0929

it could be the output of another function, because functions have values.0934

Basically, you can return anything with value.0936

When this gets called, example3_0 is going to get executed; its value is going to be inserted here, and its value is going to be the return value Goodbye.0939

So, this is going to echo the return value Goodbye, and so the script should output Goodbye.0947

If we go ahead and reload the script, we can see that that is what happens.0955

So now, one thing that we are going to talk about that we had mentioned was that you can have multiple return statements within a single function.0966

For example, if we have a function that accepts one parameter, we can maybe conditionally return a value, based on the value of that parameter.0976

For example, we create an if statement that says, "If param equals the integer 1, 0986

then we are going to execute a return statement that is going to return the string 1."1000

"Alternatively, if param equals 2, we are going to have it return the string 2."1007

So in this case, when this function gets executed, you can see that there are two return statements.1023

If param is equal to the integer value 1, it enters this if statement block, and it executes this return statement, and the function exits.1027

So, none of the remaining code gets executed.1034

If parameter equals 2, it is going to not enter this if block; it's going to enter this elseif block, and then it is going to return the value 2.1038

We could additionally add an echo statement here that says, for example, param is not equal to 1 or 2.1045

And also, what happens with a function is: if no return statement is specified, 1059

the function just returns whenever it executes the last statement within the function.1063

So here, if param doesn't equal 1 or 2, this statement is going to get executed.1070

However, if it does equal 1 or 2, the function is going to return up here or right here.1074

And this echo statement won't get executed, or if param is equal to 1, none of this will get executed, as well.1080

That demonstrates a function that can have multiple return statements.1088

For example, if we call this function (and we are just going to echo its output, because it is returning string values),1093

let's put the value of 1 in; so it should enter this first section of code; it should return the value of 1.1111

And then, because it returns, the rest of it shouldn't get executed; so this echo statement should not occur.1119

When we run this code, we can see, it outputs 1.1125

Likewise, if we just change this down here to the value 2, we can see that it outputs the value 2, 1130

and it never gets to this echo statement here, because again, once you reach a return statement, the function stops executing.1140

The other thing I wanted to demonstrate is: we have mentioned that, if a function doesn't have a return statement, it automatically returns the value null.1148

So, if we just have an empty function here, with a single statement that does nothing, and then we were to run the function,1158

we are going to run a comparison on the value returned by the function, to see if it is equal to null.1168

And we should find out that it is true.1173

So, if we run the comparison example3_2, what we are saying here is: we are running a comparison operation that is saying,1176

"call function example3_2, compare it to returned value (which in this case should be null, 1193

because no return statement was explicitly specified); it should equal null, 1197

and because it equals null, this statement should be true."1202

And with echo statements, the boolean value true gets output as the value 1.1208

That is the conversion from a boolean true to a string.1214

So, when we run this, we should see just the number 1 output; and that is confirming that this returns the value of null.1217

When we run the function, we can see that 1 is output, meaning that it did, in fact, return the value of null.1224

We have talked about how to define functions; we have talked about defining them with parameters and defining them with return statements.1236

We haven't really talked about where to define functions.1243

Typically, functions get separated into their own PHP files, known as function libraries, usually grouped according to the task they perform.1247

You might have 4 or 5 different functions, for example, that perform tasks on arrays.1255

So, you might create a function library that contains all of those functions.1261

And the function library only contains the PHP code for those functions.1265

It is just a PHP file that contains all of the function definitions.1271

And the way you access the file is by using an include statement; so if you are running a PHP script, 1279

and you need to access, for example, an array function that you have defined in a function library, 1284

you include that function library by an include statement, and then you will be able to have access to the function.1289

Now, one thing to note is: unlike some programming languages, in PHP, a function definition does not need to occur before it is called.1297

You can call a function and then define it later in the script, 1308

or call a function and then include the function library where it is defined later on in the script, and it will still work.1311

As long as the function that you are calling is defined somewhere within a script, within the script it is being called from1318

or an include file of that script, it will work.1324

The way you typically include functions, and what we are going to use in this course (or include function libraries within your code) is1332

using a new construct that we haven't talked about, called include_once.1338

It is similar to the include construct, and what it does is: it takes the file that is specified and includes it in line, in the file where the include statement happens.1344

The one difference is that, with include_once, if you specify a file to include, and it has already been included, it won't get included again.1356

For example, if in this single PHP script we have this one statement, include_once ('functionLIB.php'), 1369

which maybe is a function library, and somewhere in the script, we had another include_once function that says functionLIB.php,1376

it is not going to re-include it, because it has already been included once.1385

The reason that this is used with function libraries, as opposed to using an include statement, is:1389

if you redefine a function within the same PHP script, you get a fatal error in PHP.1394

For example, if you accidentally include the function library twice within your script, 1400

using just regular include statements, you are going to get a fatal error.1405

And similar to include, include_once also has an analog, which is called require_once, which functions the same as the require statement,1410

which throws a fatal error if it can't find the file it is trying to include.1418

But it also functions like include_once in that, if you call require_once on the same file 1422

multiple times in one script, it only gets included the first time.1428

Let's go take a look at a script that demonstrates this ability.1432

We have a file called includeOnce.php, and here we have another file called functionLIB.php.1438

This is a file that is just a function library; it contains a couple of different functions.1446

Here, in this case, we have a function called test, and a function that we are going to use in another example called outputHtmlHeader.1453

What happens is: let's say we want to use the test function within our script.1460

And let's get rid of this include statement--comment this out.1467

Now, when we run this file, we should get an error saying that the function is not defined,1471

because the function hasn't been included or been defined within this file.1476

So, if we go ahead and load the file up, it is going to say "Fatal error: undefined call to the function test."1480

OK, so we need to include the function library in order to have access to that function.1488

So, what we can do is use an include statement, include 'FunctionLIB.php'.1494

And this test function just simply outputs a simple statement; it says, "in test."1499

Now, when we run the file, everything should be OK; and it goes ahead and runs.1505

Now, however, let's say we accidentally, later, down here in our script, forgot that we had included that function library already,1509

and we run an include statement again, and try to call test again.1519

Well, we are going to get a fatal error here, because FunctionLIB.php is going to be included twice.1524

And because FunctionLIB.php has the definition of two functions in it, and it is called twice, 1529

PHP is going to see those functions being redefined, which is a fatal error.1537

So now, when we run our script, which has these two inclusions of the same function library, we are going to get a fatal error.1541

And we can see "Fatal error," and it tells you what we would expect: you cannot re-declare test.1550

It says that test, defined in the FunctionLIB, cannot be re-declared.1556

The way to fix this problem is if we use include_once on both of these statements.1568

And if we always use include_once when including function library files, we won't have this problem.1572

It is going to include FunctionLIB.php here; it is going to call the test function; 1580

and then, when we try to include it again, later on down the file, it is going to say, "Hey, I have already included this file;1585

I'm not going to include it again," and you eliminate getting that fatal error for trying to redefine the function.1589

If we save this file now, we should be able to run test twice.1597

We go ahead and load the file; we can see, we get that test was run; it says "in test" here twice.1602

Similarly, we can use...as mentioned, there is an analog require_once that does the same thing,1610

except it returns a fatal error if the file you are trying to require or include cannot be found.1623

So, we should get the same output, because it works.1630

And what that means is that this function was not included a second time.1632

Now again, the way require differs from include is that, if it can't find the specific include file 1636

(for example, if I mistype the name of it), it is going to throw a fatal error.1643

So, if we run the file, it is going to say "Fatal error": require_once wasn't able to open this misspelled function library.1647

And so, that is the difference between require and include.1657

What are the reasons to use functions?1666

The main reason, or one of the major reasons, is to take advantage of code reuse.1670

What that means is: if you have a common task that you are performing over and over again,1675

you can isolate the code into one spot (into one function), and then you can just call that function over and over again, as you need it.1678

What that does is: that is going to limit your mistakes to one place.1685

The mistakes can only occur within that one function, whereas, if you had, for example, 5 lines of code that were included in the function,1690

if you include those 5 lines of code everywhere (in 5 different files, for example), that is 5 different places where a mistake can occur.1697

If you take that code out, put it in a function, and replace it with a function call,1706

then if there is an error in that code, you only have to fix it in the function file.1712

Additionally, if you want to (for example) change the functionality of something,1718

what you can do is apply the changes all in one place.1723

So again, if you use a function call (for example) to display something, and you want to change how it is displayed,1726

instead of going through each file, editing the code that displays it,1733

if you put that code within a function, you can just go ahead and apply the changes that need to be made in one spot,1737

and it goes ahead and applies it to all the other things.1743

So, this is going to increase your efficiency as a programmer; it is going to allow you to get things done faster.1745

Additionally, it is going to allow you to reduce writing the same functionality repeatedly.1751

For example, let's say you spend a couple of hours one day developing a couple of functions that you use for working with arrays.1756

Well, maybe you have another PHP project down the road, and you want to use some of those same functions.1763

Well, by including them as functions in a function library, you can reuse those in your new PHP application.1770

If you hadn't separated them out as functions (had just hard-coded them into your PHP pages),1776

when you went to your new project (for example), you wouldn't be able to just include the function library and reuse it.1781

So, separating things into functions allows you to reuse them, not only within one application, but in multiple applications.1791

The other thing that you can use functions for is to improve code readability.1798

That is by separating your HTML and PHP.1803

Typically, you want to separate (and this is something we haven't really talked about) your HTML and PHP as much as possible,1806

because it makes for cleaner-looking code, and also, when you are working on a team (for example)1814

you might have people that are HTML developers and people that are PHP developers.1819

The less you intermingle the HTML and PHP with one another, the easier it is 1822

for different teammates to work together, without messing up one another's code.1831

If the HTML developer only works with HTML files with minimal PHP code, the chance of him messing up the PHP is limited.1836

Likewise, for a PHP developer, if he is only working with PHP files that have very little HTML, the chance of him formatting the HTML incorrectly is reduced.1845

So, you can use functions (for example) to remove large sections of PHP code from mixed HTML and PHP files.1854

You might have a 200-line PHP page, and maybe 25 of those lines are PHP code.1865

Well, what you can do is separate it out into a function, and then, 1872

when your HTML developer goes to edit the HTML on that page, all they see is one function call.1875

They don't see the 25 lines of code that that developer has a chance to mess up.1881

Another thing that you can do is...sometimes, you just have ugly mixes of HTML and PHP code.1890

When you use echo statements, you have a lot of escaping with backslashes to output quotation marks, and so on.1897

So sometimes, if you have smaller "ugly" sections of mixed HTML and PHP code, you can separate that out into a function.1905

And what that is going to do is make your PHP page that is actually output look cleaner.1916

You are not going to have to look at the messy PHP and HTML mixed together.1924

Instead, you can have it in a function, so that ugliness only occurs in one spot.1927

The other thing that some people use is: you can essentially use a function as a way to include HTML content--to replace include files.1934

That is something you might see on different projects that you work on; you might see different developers use it.1944

For example, we have a script called functionVsInclude.php.1952

Here, we are including a function library, using the include_once statement we just learned about.1964

And the reason we are doing that is because it contains this function called htmlHeader.1969

What this htmlHeader does is outputs (for example) the header of an HTML page.1973

Maybe we want to include this at the beginning of every page.1980

So, what we could do is: in our page, we could go ahead and call outputHtmlHeader.1983

And what it is going to do is take the echo statements that are in that function, run them, and then output that.1990

Now, we could achieve the same thing by using an include statement...1998

for example, if we included this file called header.html, 2003

which contains all of the same HTML that is output by this outputHtmlHeader function, and instead, we include it in here.2007

So, basically, there are two different ways of doing the same thing.2015

Some people like using functions to do that; maybe, instead of using an include statement for a header and a footer, 2017

you have two functions called outputHtmlHeader and outputHtmlFooter; it is a preference thing.2024

You may see that in different spots.2032

And one thing to also note is that here, we have all of these echo statements.2034

But as we know, with PHP you can always escape to HTML mode.2038

So, we actually could replace all of these echo statements with the exact same content that we have in header.html.2042

What is going to happen is: when we run this outputHtmlHeader, it is going to execute what is in its function body.2060

And what is in the function body is an escape to HTML and an output of HTML code.2067

And then, at the end of the function, it just returns.2074

So, that is another way to output HTML, as well.2077

So now, let's talk about improving our web application.2083

We are going to move to version 10.0, and we are going to 2086

take advantage of what we have learned about creating user-defined functions to clean up our code a little bit.2089

In checkout.php and contactUs.php, there are some rather complex boolean expressions used to validate the form data submitted.2097

For example, in checkout.php, we validate that a name, a street address, a city, a ZIP code, and so forth, were all provided.2108

It makes a complex boolean expression.2116

In contactUs.php, we verify that all three (name, email address, and comment) were submitted on the form.2120

We are going to separate those boolean expressions out into a function that is just going to return a boolean.2126

It is going to return true or false; and they are going to be called validation functions.2131

What that is going to do is make our code look cleaner, because, 2137

instead of having these long, ugly PHP statements, we have a single function call.2140

We are also going to create a function that is just going to be used to output HTML <a> tags, or anchor tags, which are HTML links.2146

It is going to allow us to pass in (for example) a URL and the name of the link that we want,2156

and it is going to dynamically create an HTML string that uses the URL and name provided.2160

We are also going to add a constant to config.php that is going to be called LIB_DIR.2168

What that is going to do is: we are going to put these functions into function libraries, and we are going to store them in a lib directory.2174

And, just as we created an INCLUDE_DIR constant in our config file, we are going to create a LIB_DIR one2181

that is just going to be a path to where we are going to store all of our function include files.2186

What we are going to be doing is creating two library files, stored in the lib directory, one called outputLIB.php, and one called utilLIB.php.2192

That is the convention we are going to use in this course for signifying function library files.2204

You will have a descriptive name for the functions that are included in the file, 2209

and then it is going be ended with the three capital letters LIB as part of the name.2214

And that is going to let you know, when you look at that file, that this is a function library.2220

This function library, outputLIB.php, is going to be used for functions that do any sort of outputting of HTML.2225

And then, utilLIB.php is going to be used for utility functions.2232

For example, that is where we are going to put our validation functions; 2239

they are functions that perform utility operations you can use within your web app.2241

So, we are going to edit checkout.php and contactUs.php.2247

What we are going to do is take out the complex boolean expressions and replace them with the validation function.2252

We are going to edit config.php, so that it has this updated content, LIB_DIR.2259

And then, we are also going to update store.php to make use of the function we are going create up here2264

that is going to allow us to create HTML anchor tags.2269

Let's go take a look at the code; for example, if we look at version 9.0, if we look at checkout.php (this is version 9.0),2276

and if we scroll down to where we do the data processing, we can see that there is one section down here2296

where we are validating the shipping information that was provided by the customer.2304

And if you look, this is a particularly ugly and complex boolean expression that is validating all of the data.2308

And so, what we can do is take that out and put it in a function that returns the boolean value of that expression.2317

And then, we can replace it with a single function call, and that is going to make it look cleaner.2324

For example, we replace that boolean expression; instead, we just have a function call down here, called isValidCustomerData.2328

And the function name has a descriptive name; typically, functions that return boolean values have is prepended to them, as the first part of the name.2338

So, isValidCustomerData is going to tell us about whatever we are passing here--is this valid customer data?2350

And so, we are getting the same functionality, but we are doing it in a simpler, cleaner statement.2358

Likewise, in contactUs.php, we validate the form to make sure that an email, comments, and name were provided.2366

What we can do is take this boolean expression out, and replace it with a simple function call that says isValidContactInfo.2375

Now, the other thing that provides is: let's say, later down the road, for these validation functions, we want to provide more validation.2384

Maybe we want to say that "state" has to be a certain state, or for the contact information, that an email address has to meet a certain format.2391

For example, it has to have an @ symbol; it has to have the domain name and the username as part of it.2400

Well, we can add that to this isValidContactInfo function, and this line right here will never change.2405

That added code won't show up in our HTML file.2412

So, we are going to keep the PHP and HTML as separate as possible.2415

And what that is going to do is allow us to change the functionality, but we don't have to change this code here; it is going to keep this code looking clean.2420

So, if we go to the LIB directory of version 10.0 and open up utilLIB.php, we can see these two functions that we have created.2428

The first one was called isValidCustomerData, and what we do is, from checkout.php, pass it the customerData variable, 2442

which is an associative array that represents all of the GET data passed to checkout.php.2452

It goes ahead and uses this customerData parameter, and what it does is performs the same validation function that we had in the script.2459

It says, "Just make sure that each of the different fields are not empty."2466

If all of them are not empty, it is going to return true, so that we can know that it's valid, and proceed as appropriate in our checkout.php.2470

Likewise, for the contactInfo validation, we have an isValidContactInfo function.2483

We pass it the contact information that was submitted on the Contact Us form, and we perform the boolean validation function.2491

If it returns true (that all of the information was provided), then it returns true to our script, and it can go ahead and execute.2500

When it calls this, if this is true, it outputs the appropriate page title (for example).2508

If not, we are going to use our error functionality and set up an error message saying "You must complete all of the fields in this form,"2513

and also set our error flag (that we had talked about in previous versions) to true.2520

The other thing that we are going to do is create a function that is going to allow us to output HTML links, or <a> tags.2529

For example, if we look at version 9's store.php, we can see, we have a link hard-coded into each page2538

that is a link to each different item in the catalog (item-1001, 1002, and 1003).2545

What we can do is create a function that will allow you to pass two parameters or arguments to it,2552

one for the URL of the link that is going to be used for the href, and then also one value 2560

that you can put in the body of the link, that is contained in the a tag.2566

If we open this other library file called outputLIB.php, we can see a function called outputLink.2571

It accepts two parameters, both of which are strings: a URL and a body.2580

And what we can see is that it creates a link variable; and what it does is dynamically creates an a tag.2585

It sets href equal to the URL specified; it sets the body of the a tag equal to the body specified.2598

This is a useful function, because this is one of the ways of eliminating ugly PHP/HTML mixed code from your file.2606

And it is not too prevalent in this example, but we will see it more, as our application gets more advanced,2616

and our URL's that we are using, and our expressions to set the value of URL's, get complex.2623

This is going to neaten them up, because now, instead of having a statements, which included echo statements from PHP,2628

we have replaced it with simply a call to outputLink, which we echo.2642

And we pass it the URL that we want (in this case, for item-1001), 2648

and then we provide it the name that we want to be in the tag (which is going to be the item's name).2652

And we do that for all three of these.2658

And if we go and look at version 10.0, this is the store home page.2661

We can see, if we look at the source, that our links are just as they were before, except they have been created by this outputLink function.2672

And they work just as they had before.2686

One thing to note: if you have a chance, after the lesson, to look closer at the files that we have created,2693

particularly function libraries, you can see that to each function, I have added a lot of comments at the beginning.2702

It is always good to add comments that provide a lot of information to the programmers about your code.2710

For a function, I usually have a comment that states the purpose--what the function does.2716

In this case, it is saying it is outputting a link that is an a HTML tag, an anchor tag.2722

I also described the parameters that the function takes, so somebody can quickly look at this and say,2729

"OK, it takes 2 parameters, one called url and one called body, and this is what they represent."2734

"The url represents what is going to be used in the href attribute with the anchor tag, 2738

and body represents the text that is going to be output as the body of the anchor tag."2744

And then, I also have a return value section that says, "This function returns a string, 2748

and the string that it returns represents a well-formed HTML anchor tag."2753

How do we make these functions available to our scripts?2762

That is where the config file comes in; we have updated config.php, and what we have done is created a new constant called LIB_DIR,2764

which states that the function library directory is called LIB, and it is off of the document root.2781

And that is where all of our function libraries can be found.2791

And then, what we do is add to our include section, using the include_once directive.2794

We include each of the two libraries that we are going to use, outputLIB.php and utilLIB.php.2799

This is going to make them available to all of the files where config.php is included.2806

You can see that we make use of the LIB_DIR constant, which says that output.php is in this LIB directory, and you include it one time.2810

And so, that is how we make those functions available to our web application.2819

One thing I want to comment on is outputting of HTML in functions.2827

It is usually preferable to refrain from directly outputting HTML within functions by echo statements or HTML, when it's possible.2831

The reason for that is that, if you have function libraries (for example) in multiple different library files in your code,2840

and you are calling different functions and different scripts,2847

and one function in one library outputs some HTML; another function in another library outputs some HTML...2850

it makes it hard for your HTML editors (which may be you, or it may be a separate person) to figure out2856

where they can go to edit the HTML, so that it is output properly.2862

So, by not outputting HTML in your functions, and only doing it in the actual PHP pages that are going to be shown,2865

it allows the person editing the HTML to find it all in one location.2874

Now, sometimes it is necessary to output HTML within functions, and the recommendation that I have2880

is to put output functions in their own separate library.2887

So, for our example, in this web app, we have created a library called outputLIB.php2890

because that generates HTML (in this case, it generates anchor tags).2897

We are going to build out that library as this application develops, and you are going to see that there is going to be more complex HTML output.2902

But by putting it in that one library, your HTML developer knows that if the HTML that they need to edit is not found 2909

in the actual PHP pages that are being output, then it is going to be found in this function library that is defined for output functions.2915

One other thing to mention is that, if you have some functions that generate short segments of HTML2923

(for example, our outputLink function that just generates a link to output),2929

it is highly preferable to generate the HTML content as a string and return that string, rather than echoing it directly in the function.2934

For example, in our outputLink function, we return this link that we created.2943

We could, instead, just echo it directly here--echo link--and we would achieve the same thing as what we had done before,2952

if we just replaced the echo statement here with outputLink.2964

So, it's going to call outputLink, and it is going to echo that.2967

Now, there are a couple reasons why that is not preferable.2969

Let me go back and change it to the way it was.2973

The first one is that it reduces the flexibility of your application.2978

For example, if we return the string, then in the store.php, because we are returning it as a function and not directly outputting it,2981

we can perform another operation on it, whereas if it just gets echoed, it is echoed to the output and there is nothing you can do with it.2993

Maybe we want to include that HTML as all uppercase, so we could use the strtoupper function.3001

Well, because we returned it as a string, we could use that string as a value supplied to the strtoupper function.3007

And then, when we echo it, we can make it all uppercase.3013

And so, it gives us the flexibility of altering that; and in this case, it's a function chain.3018

So, when we go and reload our home page, we can see that (I guess I just did it for the second one, item-1002) it is output in all uppercase.3023

And if you look at the page source, you can see that even the HTML code itself, href and all that, was capitalized, as well.3040

That is one thing that is a benefit of returning a string, rather than echoing it directly.3053

The other thing is that, if you want to create complex echo expressions--for example, let's say we wanted to echo3060

the string "Hello" and then output that link by concatenating it--what is going to happen is: right now, it is going to work as expected.3070

It is going to output Hello; it is going to call the outputLink function, return that <a> anchor tag, and then output it all together.3086

So, if we go and view our code (oops, I forgot to get rid of the extra parentheses here), we can see that3094

it outputs Hello, and then it outputs the anchor tag, as expected.3115

Now, in our outputLink function, if we had instead echoed it directly, something interesting is going to happen.3120

Now, when we call this function, it is going to say "echo this string right here."3134

And in order to echo this string, what PHP is going to do is concatenate the output of outputLink to Hello.3141

Well, in order to do that, it has to call outputLink and find out what its value is.3149

So, when outputLink gets called, because we have echoed the link now, it is going to echo it.3153

So, before this concatenation can occur, outputLink is going to be echoed; so the link is going to end up before Hello.3159

For example, if we go ahead and run this file, we can see that, even though in the echo statement, we have put the outputLink3167

tag at the end of the concatenation operation and Hello at the beginning, the order gets reversed.3179

And that is because, since the function didn't return the string, we can't concatenate it in our echo statement.3184

Instead, it just gets output immediately when it is evaluated.3191

That is one of the problems that that can cause.3195

Just really quickly, I want to finish up with talking about coding conventions.3198

Functions, as you have seen in the examples, are going to be formatted in the same manner that we format if statements,3202

in regards to the placement of curly braces and indentation, the one difference being 3209

that the if keyword is going to be replaced by the function keyword.3213

The other thing is functions with multiple parameters: each function in the parameter list is going to be separated from the previous one3217

by a comma and a space, so it is going to be param, and this is going to be a space before param2,3225

as opposed to not having the space there.3235

The other thing that we are going to do is: we are always going to define all of the functions for our course within function library files.3238

You can define them within a script, but then that reduces the ability to reuse those,3244

because then, for example, if you defined it in contactUs.php, if we defined in a email function within there, for example,3250

then if we ever wanted to use that again, we would have to include that whole PHP page.3258

And so, in order to get access to that function, what that is going to do is include all of the HTML, as well.3262

So, we are going to include all of our functions in library files.3267

For the homework challenge, I just want you to create a PHP script that is going to create a function called add, your first user-defined function.3275

It is going to accept two integer parameters, and what it is going to do is return a string that is the sum of those two integers,3284

surrounded by the bold tags used in HTML.3291

It is going to take in two integers, and it is going to return a string.3296

And then, I want you to call the function from your script and output the result.3299

And what that is going to do is a couple of things: it is going to teach you how to define your own function;3303

it is going to teach you how to use multiple parameters in a function;3310

it is going to teach you how to use a return statement; and then, it is also going to echo 3313

the comment that I had about returning strings, as opposed to echoing them directly.3317

Then, what I want you to do is get practice creating function libraries: go ahead and create a function library called mathLIB.php.3323

And put the function within that file; and then, in your main script, when you have moved it out, it gets deleted.3331

And then, use an include_once statement (to get practice using that) to include that LIB file in your script.3338

And then, try calling the function again, to make sure it still outputs the sum, formatted in bold.3344

Just be sure to remember to format the function according to the course's coding conventions.3349

That ends today's lecture; thank you for watching Educator.com--I look forward to seeing you next time.3355

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to go over how to set up your development environment.0005

Specifically, we are going to talk about what development environments are, and then go over a couple different kinds of development environments:0010

one known as a remote development environment, and one known as a local.0017

We are going to talk about the software that we are going to be using in this course for our development environment.0021

And then, we are going to go over a couple of concepts related to web servers, and what is known as local development.0026

Basically, we are going to be talking about the loopback IP address, and we'll explain more about that, as well as the localhost host name.0033

We are also going to talk about the concept of a document root.0040

We are also going to go over a description of the different kinds of text editors that are available,0044

and go over our PSPAD installation, which is the text editor that we are going to be using for this course.0049

And then, we are going to finish up with a section that provides some additional resources for finding help in setting up your development environment,0055

and then also, introducing our first homework challenge.0062

What exactly is a development environment?0066

Well, essentially, it is just a setup for a programmer to be able to write and test and debug their software.0069

What we have done for this course is: we have chosen a default development environment setup that we are going to use throughout the course.0076

The reason for that is that, unfortunately, one of the biggest roadblocks to new PHP developers0084

is actually just getting their development environment set up so that they can actually run PHP code and test it.0090

Part of this reason is that PHP and Apache (which, as we learned in the last lesson, are two pieces of software that need to be configured to work together)0096

can be quite difficult to do that.0106

And so, we are going to install some software for this course that is going to help ease that problem.0108

For our default environment that we are going to be using, we are going to be running it on a Windows 7 platform.0115

The reason for that is: I feel that that is the most popular operating system, and will be able to reach most of the students out there,0121

the idea being that you will be able to mimic the steps that we take in this lesson,0127

so that you will be able to get your development environment set up with as much ease as possible.0132

Additionally, we are going to be including software components as part of our development environment that have a couple of key features.0140

We are selecting components that are free, so that all of the students will be able to download them.0148

We are picking things that are easy to install and configure.0152

And additionally, we are picking software that is available for most major operating systems.0156

So, even though we are going to be walking through the setup of the development environment on a Windows 7 machine,0160

all the software that we are going to be using (except for the text editor) is available for most operating systems,0165

so if you develop on a Macintosh or Linux or Unix machine, you will be able to get the same versions of the software we are going to be using.0172

The text editor, as mentioned, is only available on Windows machines; but there are literally hundreds of text editors out there on the Web,0180

so doing a simple Google search should be able to find you a compatible text editor that will work for use in this course.0187

Additionally, the software that we have chosen is well-documented.0195

It has a large user base, so that there is a lot of information out there that will help you if you get stuck in configuring it,0199

for example, if the default configuration that we set up in this course doesn't work for you.0205

Additionally, the software that we are going to be using is actually software that is used in the real world.0210

We are going to be using the latest version of PHP, and also the Apache web server, which is the most common web server that is used in the world.0214

The other thing to note is that the development environment we are going to be setting up for this course0223

is going to be the same development environment that we are going to use in the Advanced PHP course, with some slight modifications.0227

So, for those of you that continue on in the PHP course sequence here at Educator.com, 0233

you will be able to continue to use that same development environment, without having to reinstall everything over again.0238

One thing I want to talk about first is: there is a thing about this remote development and local development.0246

Basically, "remote development" refers to where a programmer develops their code, or their websites, their PHP pages,0252

on their local machine, and then the way that they test them is by uploading them (typically by FTP)0260

to a remote server, where they can be run and be tested.0267

Now, we learned in our last lesson that, in order to basically view and serve PHP pages, we need three pieces of software.0271

On the client side, we need a web browser to request the web page to be viewed.0283

On the server side (in this case, it's called the remote server), we need the Apache web server that is able to serve HTML documents,0288

and also is able to pass on--if PHP files are requested--those requests to the PHP Interpreter,0296

so that the PHP Interpreter can generate HTML output and pass it back to Apache to pass it back to the client.0304

So, in order to be able to serve and view PHP pages, we need a web browser, the Apache web server, and the PHP Interpreter.0310

Additionally, for development, we need a way to code our text files or our PHP files that we are going to be using.0321

And so, we need a fourth piece of software that is going to be a text editor.0327

And basically, the way that it works in a remote development environment is that, typically,0332

the web browser and text editor are on your local machine, and the remote server contains the web server0336

and the version of PHP running that is going to generate your dynamic web pages.0343

What happens is: you will create some PHP file on your local machine (for example, a .php file).0349

And then, what you will do is: you will typically use FTP to upload that PHP file to your web server.0356

Then, in order to test the software, you are going to open up your web browser, 0364

create an http request for the particular PHP file that you are wanting to test,0369

and then the typical process for loading a PHP file occurs.0376

Apache is going to let PHP know that a PHP file has been requested.0380

PHP will load it from the hard drive, parse it, and generate HTML, which it will pass back to Apache, which Apache then forwards on to the client.0385

This is basically the scenario that happens.0396

For those of you that have been Web developers before, that have a web host,0397

typically what you do is: you develop your HTML files on your local computer.0402

You upload them to your web host, maybe to a temporary directory, and then view them there to test them out.0406

This is an example of remote development.0412

What we are going to be doing in this course is setting up a scenario for a local development, or a local development environment.0415

What you can see is that, over here, we actually don't have this remote machine involved anymore.0421

All of the software that we had in the remote development environment, we are still going to have,0426

but it is all going to be run on our local development machine.0431

So, on whatever computer you are developing on--your Windows 7 machine--we are going to have the Firefox web browser software installed.0434

We are going to install the Apache web server; we are going to have PHP installed; and then, we are also going to have a text editor installed.0442

What happens is: basically, there are a number of benefits to doing this.0450

A lot of it has to do with increasing your efficiency as a developer, because now, when you create a PHP file,0455

in your text editor, on your local machine, instead of having to FTP it across the Internet to Apache,0464

that FTP simply becomes a local saved file to your hard drive.0471

Because your Apache server is running on your local computer, Apache and PHP just need to load that file from the local hard drive.0475

So, we don't need that FTP operation, and we eliminate one of the network interactions that takes time.0482

It takes time to upload files by FTP.0491

Additionally, when we want to test a file, we don't actually have to go out on the Internet.0495

We just point our browser at our local Apache server, and it is still going to generate an http request,0499

but it is not going to go out over the Internet.0505

It is going to stay local within your computer.0507

So that, again, eliminates another network connection that you have.0510

Another added benefit of this is that, by having your web server and PHP all on your local development machine,0513

you can actually develop while you are offline--while you are not connected to the Internet--0520

because you don't need to be able to FTP to a remote server, nor do you need to connect to a remote server to test your pages.0524

The other benefit that you get from having these things installed locally is that you have access to all of the configuration files--0532

for example, for the Apache server and for the PHP Interpreter.0540

You have access to those configuration files, whereas for example, if you are using a web host and have a shared web hosting account,0545

you may not be able to alter the PHP configuration.0552

Now, because we are going to be developing, 0556

we may want to set some configuration settings that will be useful for development, so we want to be able to make those changes.0558

And also, as we are learning PHP, we are going to be changing some of these settings.0563

And by having that configuration file that we can edit on our local machine, we will be able to experiment with different settings,0567

and it will help us in learning PHP and how to do PHP development.0574

The software that we are going to be using in this course, basically, 0583

is the four pieces of software that we talked about: a web browser, Apache, PHP, and a text editor.0586

For the web browser, we are going to be using Firefox, which is an open source web browser that is free.0592

One of the main reasons we are going to be using it is because it has an add-on called Firebug,0600

which basically adds a bunch of Web developer tools to the browser that make it easier to do Web development,0603

and also that we will be able to use to help us diagnose problems with our PHP scripts,0610

for example, when we get into dealing with input data from HTML forms, such as something known as GET input data.0615

Actually, if we go and take a look--I have already installed Firefox, and basically, this is the link provided on that slide,0623

which will also be provided in Quick Notes, to where you can download Firefox.0630

Simply click on the download link; it is going to pop up a window allowing you to download an executable file.0633

And you simply run and install it, just as you would any other Windows application; it's a pretty straightforward and quick process.0639

Now, to install the Firebug add-on--that is actually something you do directly from Firefox.0646

The way you do that is: you go to the Firefox menu; you click on the Add-ons option, and Get Add-ons is going to load up.0650

In the Search Add-ons box, simply type Firebug.0659

What that does is searches all of the plug-ins and add-ons that are available for Firefox.0662

And we can see that Firebug pops up as one that is available.0668

We simply click on the Install button; what it is going to do is actively download that add-on in real time.0672

It has basically already installed it in this short amount of time, and then it asks you to restart Firefox in order for the changes to take effect.0680

If we click on Restart Now and wait a couple of seconds while the browser reloads (and actually, you can see that it already has),0688

what you will notice, actually--it's kind of subtle, but in the bottom right-hand corner of the screen, you will notice this little bug.0702

If you click on it, it opens up this tool panel at the bottom.0709

This is what Firebug is: it's a panel of different tools that allow you to diagnose and figure out problems that are going on with your web application.0714

And so, that is how you know it successfully installed--the little bug appears down here.0724

You can go ahead and close that by clicking on the bug again.0727

That is Firefox and the installation of the Firebug add-on.0730

The other piece of software we are going to be installing is actually a software distribution; it is called XAMPP.0736

What it is: it is a combination of a number of different pieces of software that are combined together in one distribution,0742

and set up so that they are easy to configure with one another.0749

In particular, XAMPP contains PHP (in this case, for the version we are going to be using--1.7.4).0753

It contains PHP version 5.3.5, and it contains the Apache web server version 2.2.17.0760

What we do is: we simply download this software distribution.0768

It is going to contain Apache; it is going to contain PHP, along with a number of other different pieces of software.0771

For example, it is also going to include the MySQL database.0776

And what it does is: it also provides some configuration files that make it easy for you to get Apache and PHP set up to work together.0780

That is one of the main reasons that we are using this software distribution: 0788

because getting Apache and PHP to work together can be a very difficult task.0792

Also, the other piece of software that we are going to be using, that is mentioned, is the PSPAD text editor.0798

It is a Windows-based text editor, and it can be accessed at this link.0803

You simply go and download the executable file and run it, just like you did for Firefox; it's pretty simple.0807

For XAMPP, it's going to be a little bit different.0814

There are a couple of different options available at this link, which again, will be available in the Quick Notes.0816

I'm going to have you download the ZIP archive, and not the EXE file.0821

And actually, I'm going to walk through that XAMPP installation now.0825

The first thing for the XAMPP installation is actually: let's go look at the XAMPP website.0831

It is at a website called ApacheFriends.org; we want XAMPP for Windows.0837

If you scroll down this page and pull it up a little bit, you can see the different downloads.0842

There is going to be a Windows Installer and then a .zip file.0847

What we want is: we want to install the .zip archive; we want to download the .zip archive.0853

I have already downloaded that; and the first thing you do is: we are going to unzip that software distribution.0859

Now, I have actually already gone ahead and done that, because it takes a while; it's a pretty large file--it takes a while to unzip all of the contents.0869

But for this course, we are going to unzip that XAMPP software distribution into a directory called XAMPP.0874

You should put it in your Windows User directory.0882

The reason for that is related to permissions: we could install it in the Program Files directory, or maybe on the root hard drive (for example, the C drive);0886

however, because one of the things we mentioned that we want to be able to do as new developers is0895

to play with the configuration files, if you install, for example, the XAMPP distribution in the Program Files directory,0900

you run into problems when trying to edit the configuration files; you run into permissions issues.0907

Typically, that can be avoided by placing the XAMPP distribution within your User directory, 0912

because you have full read and write permissions, 0917

which will allow us to pretty easily change the configuration for PHP, and if we need to, Apache as well.0919

You unzip the file into an XAMPP directory in your user directory, and then the next thing you do is: 0926

you run this setup script, or a batch script, that XAMPP provides for you, that is going to get everything configured and set up to work together.0932

If we go to where...Educator1 is the name of our user directory on this computer--0941

we have gone ahead and unzipped the XAMPP distribution into the XAMPP directory.0947

And you can see here, this is the contents of the XAMPP distribution.0954

What we are going to do is run the file called setup_xampp.bat, and that is the batch file that is going to set up XAMPP on your computer.0958

If we go ahead and click on that, what is going to happen is: a Windows command prompt is going to pop up.0966

And you may or may not be able to see the text in this window, but it basically says, in this case,0971

that it was successfully installed and configured, and press any key to continue.0977

If we go ahead and do that, XAMPP is properly set up on this computer.0980

Now, that being said, the next step that you want to take is to verify that the installation actually worked.0988

There can be some problems that occur.0993

The first thing that you do is: you start XAMPP; and you do that by running a file called xampp-control.exe in the XAMPP directory.0996

If we go ahead and go to our XAMPP directory, and we double-click on xampp-control.exe, this control panel for XAMPP is going to pop up.1005

And you can see, it has a number of different buttons on here.1013

The first one is a start button that relates to the Apache web server.1016

The next step that we are going to take, when we start XAMPP, 1020

is to go ahead and click the Start button next to Apache, so that our Apache server will be up and running,1023

because we need that to serve files locally on our computer.1029

So, assuming everything works right, you will see a little message here that says "running," that lets us know that Apache is up and running.1032

One recommendation I would have would be to put a shortcut somewhere to this xampp-control.exe,1040

for example, on your taskbar, so that it is easy to access, because when we are changing configuration files,1045

you are going to want to be able to access that to start and stop Apache.1052

The next step that we are going to do, now that Apache is started and we know that that was successful1057

(if it wasn't, we would have gotten some sort of error message):1061

we are going to open our browser and browse to this address: http://127.0.0.1.1064

What that is: basically, we are saying we want to view the contents of the root of a web server at this IP address here, using the http protocol.1072

And if XAMPP was installed successfully, and Apache works correctly, we should see a splash screen up here.1085

So, if we go to our web browser, we open a new tab, and we go to http://127.0.0.1, and we click Enter,1092

(oops, I'm sorry, I mistyped http),1104

we see the XAMPP splash screen that is going to allow you to select a language.1109

For this course, we will be using English, so we click the English link.1113

What comes up is the XAMPP control panel; it is another one of the advantages of using a software distribution like XAMPP.1116

It provides a control panel that allows you to configure and play around with the different pieces of software that come with it,1125

especially things besides Apache and PHP, like your MySQL database and so forth.1132

So now, we know that our XAMPP distribution is up and running.1138

If you get to this point, you know that you have successfully installed XAMPP, and your Apache server is working correctly.1140

Now, what you will notice from the last slide is that we went to the address 127.0.0.1, which is an IP address.1149

It is known as a loopback IP address.1158

Basically, what it does is: when you type that in your web browser, your computer knows that when you go to that address,1160

it is not going to search for a computer on the network that has that IP address.1167

It knows that that address refers to itself--the local computer.1171

When you type that address in your web browser, your computer is going to know that it means,1175

"I want to look for a web server that is running on my local machine," so it is going to look for a local Apache web server.1179

Now, one other way to refer to this IP address is using the host name localhost.1188

Localhost is a name you can type in your browser; it works like domain names...for example, just like amazon.com does.1194

Whereas amazon.com, using DNS, translates to a specific IP address--1200

and it's an IP address that computers use to communicate, but you can access it in your web browser by typing amazon.com,1205

in that same way, we can use localhost and type that host name in our browser,1211

and that is going to refer to this loopback IP address, as well.1215

For the remainder of this course, we are always going to be using localhost to refer to our local web browser,1221

rather than the loopback IP address.1226

We are going to do that for pretty much the same reason why, when you go to amazon.com,1228

you don't type in the IP address: the domain name or the host name is easier to remember than the IP address.1231

Now, because those refer to the same IP address (localhost refers to 127.0.0.1), 1238

if we go back to XAMPP or to our web browser, and we type http://, and type localhost this time,1245

what we should be able to do is make a request to our local web browser.1255

And if we hit Enter, we can see that that actually happens.1262

So, localhost and 127.0.0.1 both refer to our local machine with Apache running on it.1266

Now, one thing I want to talk about is a term called a document root.1277

Basically, what a document root is: it refers to a folder on your local hard drive1281

that contains all of the files that are accessible by your web server.1286

Basically, only files that are contained in a web server's document root or its subfolders are typically accessible by the web server.1291

For example, for those of you that have worked with web hosts before,1301

maybe your document root was named something like public_html, or www.1304

And basically, what your web hosting provider would tell you--they would say,1310

"Any files that you want to be made available on your web server--you put them in these directories."1313

For example, every file on your computer is not available by your web server; only files that are put in these specific directories--1320

the document root or its subfolders--are available by the web server.1327

For Apache and the XAMPP installation, the document root is a folder named htdocs that is located in the XAMPP root installation folder.1334

For example, if we go and look at our XAMPP directory, we can see, there is an htdocs folder.1347

And anything that we want to be able to test--that we want to be able to view through the Apache server,1351

which is going to be all of our PHP files, needs to go in this directory or below it.1356

What I am going to do is create a folder that we are going to be using throughout this course1361

to contain example files and the web application we are developing; and I'm going to call it intro2php, with the number 2.1364

So basically, I have created a new directory within our document root.1375

And then, I am going to use PSPAD (which we haven't talked about yet, 1379

but it's the text editor that we are going to be using for this course) to create a simple HTML file.1382

It is going to be a bare-bones file that just has the HTML and body tags, as well as a header tag.1391

We are just going to include a header that says some message.1405

We'll call the file sample.html, so we're going to say, "This is sample.html."1412

My typing is off.1423

When we go ahead and try to save this file using the Save As command, we are going to browse to the htdocs folder in our XAMPP directory.1429

And within that, we are going to browse to the intro2php folder, and we are going to save this file as sample.html.1441

Now, if we go back and we look at our intro2php file, we have this sample.html file here.1452

Well, because this directory (intro2php) is contained within our document root,1458

the files within it are accessible by our web servers, so we can use a web browser to access them.1462

So, because when you go to the localhost and just look at the root directory, what it shows you is the contents of the document root--1469

well, we are not interested in the document root; we are interested in the sample.html file in the intro2php directory within the document root,1481

so we are going to type the URL: intro2php/sample.html.1490

And as you remember, when we talked about URL's, everything after the host name is a path.1496

So, we are saying that we want to find the sample.html file in the intro2php directory 1502

that is within the document root of our web host (in this case, our local web server).1509

And if we go ahead and browse to that page, we can see that our web page loads up.1514

And if we look at the code, we can see that load up some...we can see the source code that we typed.1518

And so, that is how URL's map to files in your local file system.1525

In this example, sample.html, contained in the intro2php directory, contained in the htdocs directory,1533

is accessible by localhost/intro2php/sample.html.1541

That is how URL's map to files within the file system.1547

And also, this is typically how local development is going to go: you are going to be creating a text file in your text editor.1553

You are going to be saving it somewhere within the document root (in this case, into the intro2php folder).1560

And then, using your web browser, you are going to browse to it using localhost to see if it works as expected.1565

Now, I just want to talk a little bit about text editors.1574

To code PHP files--PHP files are just essentially plain text files, and there are a number of different text editors out there which can do that.1577

There is sort of a spectrum of text editors.1588

On one end, you have, for example, Windows Notepad, which is basically a bare-bones text editor.1590

It just allows you to create a text file and save it.1594

On the other end is something like Zend Studio, which is an IDE, or an Integrated Development Environment.1598

What that does is: that is sort of like a text editor on steroids.1604

It provides all sorts of features in addition to just being able to edit text files.1609

For example, it allows things like code completion, code refactoring...it might include some debugging tools or some build tools.1616

What we are going to be using is PSPAD, which is somewhere in the middle of the spectrum.1623

It is actually more towards the bare-bones end.1627

And essentially, PSPAD is a bare-bones text editor with a few little features added on top of it that we are going to make use of.1629

One thing to note is that we are not using Zend Studio or any of the IDE's that are available out there.1638

And there is a specific reason for that, and that is because these IDE's, while very powerful1643

(and they can really make a programmer's life much easier by doing things automatically),1648

that is part of the problem: for example, it will do things automatically for you behind the scenes.1654

And as a new programmer to PHP, you want to really know what is going on.1658

We want to be able to do everything ourselves, so we can really learn how it is going on.1662

If we use the IDE, it is going to be doing things, and we are not really going to be understanding what is going on,1666

which is why we have chosen a more bare-bones text editor.1671

Now, that said, once you become an experienced PHP programmer, it would be great to move to the IDE.1675

That is what professional programmers use, because you allow it to do mundane tasks that you understand how they work,1680

but they are sort of a pain to do; let them do that for you.1688

We need to sort of work through those pains in order to see what is actually going on behind the scenes, to learn how things work.1691

PSPAD is installed, as mentioned before, just by downloading an EXE file from pspad.com.1699

You are going to download the Windows Installer; and when you install it, you just run through it like a typical installation.1707

This is what PSPAD is going to look like when you open it up.1714

Now, there are a couple things to note.1716

One is: it has sort of a sidebar here that you can disable if you want more screen real estate.1718

You simply do that by clicking on this Tool Panel button in the View bar.1724

Additionally, we are going to be debugging our PHP application, so we are often going to want the line numbers of where errors occur.1730

There is an icon in the Menu bar at the top over here that, when you click on it, goes ahead and shows the line numbers of the pages.1736

That might be something that you want to do.1744

Additionally (and the main reason we have chosen PSPAD)--1747

the additional feature that it provides on top of Windows Notepad is what is known as syntax highlighting.1751

What that does is provides visual cues to you as the programmer to make your files easier to read and to see if you made mistakes.1756

For example, this file, sample.html, that we have right now, that has been saved, doesn't have any syntax highlighting.1764

Everything looks the same--it is all the same color.1770

However, if we go down here, and we click on Text at the bottom of the screen,1772

PSPAD allows us to pick a syntax to view the file in.1776

So, if you click on HTML, you can see that now, the (I'm going to go ahead and blow up the text size here)...1780

You can see that it has color-coded our tags, which provides visual cues that you are using one tag over another.1798

And then, also, for example, let's say we improperly close this H1 tag.1806

Well, now it turns red; and so, that provides you a visual cue as a programmer that, 1811

"Hey, you have made a mistake in your code, and you can go back and correct it."1815

That is the advantage of using PSPAD, and is why we have chosen that, for this added feature.1818

Now, I just want to talk about finding help if you get stuck in setting up your development environment.1827

As mentioned, it can be kind of complicated, setting things up; 1832

and if things don't go as smoothly as they have in this lecture, 1834

I wanted you to be able to have some resources available to go out on the Internet 1837

and be able to find ways to help you solve your problems.1842

Fortunately, there is an abundance of resources on the Web.1846

Two useful ones (and these links will be in the Quick Notes, as well) are: 1848

the first one is for the PHP manual, and this is the installation instructions on the manual,1851

and then also, the link to the documentation for the Apache web server.1856

Additionally, often, a quick Google search will direct you to the answers that you might need.1861

And one thing I want to note is that one of the more common problems in getting Apache up and running and to run locally on your machine1867

is if you have another program that is already bound to port 80.1873

As we learned, a web server takes http requests by listening on port 80.1878

And so, if you have a program--only one program on a computer can be bound to that port at the same time,1884

so if you have another program that might already be bound to that, when Apache tries to start, it is going to have problems.1888

That is one of the more common problems.1894

Now, I am going to introduce your first homework challenge.1898

The first thing I want you to do is go through and complete and verify the setup of your PHP development environment,1900

just like we did in the course.1905

And then, I want you to go ahead and--after you have seen the splash screen and seen that everything works--1907

go ahead and stop Apache and XAMPP; and that will give you practice with stopping and starting those two,1912

because that is something you are going to be doing often.1916

Then, I want you to use PSPAD to create a file named sample.html that contains whatever random HTML markup you want.1919

And then, I want you to save it in the appropriate folder on your computer so that you can browse to it at this URL here.1926

You are going to have to understand what we talked about when we talked about the document root1934

and where the document root is on the XAMPP installation, so that you can do this file successfully.1938

And then, I want you to go ahead and attempt to view sample.html at this address.1944

And assuming you followed step 2 above, the XAMPP and Apache are going to be turned off, 1948

so you are going to get an error saying that you can't make a connection to 127.0.0.1.1952

What I want you to do is go ahead, restart XAMPP and Apache, and then verify that you can successfully view that sample.html page.1959

That is going to give you practice learning how files on your local hard drive map to URL's in a web browser.1967

And then, also, I just want you to verify that you can view that same file, using the localhost host name, as opposed to the IP address.1975

That is the common convention that we are going to be using throughout the rest of this course.1981

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1987

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be talking about the concept known as variable scope.0004

Specifically, we are going to be talking about what variable scope is.0011

We are going to be talking about a special word in PHP, the global keyword.0014

We are going to go into more detail about superglobals, which is something we have mentioned 0020

when we have talked about the _GET and _SERVER superglobal arrays that we have used in previous lessons.0023

We are going to talk more about actually what superglobals are.0031

We are going to talk about some of the pitfalls of using what are known as global variables.0033

We are going to talk about when variables are to be defined.0038

And then, we are going to finish up with an example that puts together all of the stuff that we have learned in the lesson,0042

and then quickly just talk about something that doesn't fall under variable scope, but is a related issue; it is called function scope.0049

What is variable scope? Well, essentially, variable scope refers to what in part of a script a variable is accessible.0058

For example, when we define a variable in our script, a=1, it is available within all of our script.0067

So far, all of the variables we have defined in our scripts are what are known as global variables, and have what is known as global scope.0075

And what that means is: once they are defined, they are able to be used anywhere within the file.0083

And they also can be used within any include files.0090

For example, on our web application, where we defined the pageTitle variable, when we include our header file, 0093

it can access that pageTitle variable and use it, because it is within its scope.0100

It is a global variable, so it is available to the entire script and any of its include files.0106

However, now that we have introduced user-defined functions...variables defined in functions 0111

have a different scope, what is known as local function scope.0117

And that affects the ability to use variables defined in your script within a function, and variables defined within a function within the script.0121

The reason is what is known as scoping rules.0130

Essentially, any variables that are defined within a function have local function scope, and they can only be accessed from within the function.0134

This include function parameters.0144

Let's take a look at a file called scope.php; we have a couple of functions here that we are going to get to in a second.0147

The first thing I am going to do is: in our script, we have two functions defined up here, and then we have a variable assignment statement0154

that declares a variable we are calling globalInt=25.0164

And because it is defined in our main script, as mentioned, just like all of our other variables we work with, it is a global variable.0169

So, it is accessible anywhere in the script; so when I type echo globalINT, PHP is going to know what that variable responds to.0174

That variable is going to have scope, and PHP is going to know where to find its value.0185

When I go ahead and load the page, it will output 25.0190

However, let's say (this function up here that we have created is called changeGlobalInt), for example, that we want to run this function,0197

and then change the value of this global integer from 25 to 0.0209

And that is what this function is going to do.0215

Well, 2 things to note: the first thing is that, if we go ahead and run this function, and then we echo globalInt again,0218

we are going to see that it does not get updated.0236

The reason is that globalInt is defined in the global scope (and so it has global scope),0240

but once you enter into a function, those global variables are no longer available.0246

So, even though we are referring to globalInt, which was previously defined in the script, and we are going to set it to 0,0251

this globalInt is kind of like its own separate variable; it only works within the function body.0257

And it doesn't affect this global variable defined out here.0264

This globalInt, even though it has the same name, is a local function variable..0269

So again, all we are doing here is setting the local function variable globalInt to 0.0274

The change doesn't get made, so here, when we echo globalInt, it is going to show 25.0282

When we run the function that is going to try to change the value, it is not going to work.0287

And so, we are still going to see that globalInt outputs 25, as well.0291

I just need to put a break statement here.0296

When we go around to the file, we see that 25 is output twice.0304

And again, the reason for that is that, within a function, you cannot access global variables.0307

At the same time, not only can you not change them, but you cannot access them, either, to output them.0317

For example, let's say we wanted to echo globalInt.0325

Now, one would think, "OK, we have run our script; we set globalInt to 25; we have output it."0330

"We call this function, and the first statement is echo globalInt--well, we would think since globalInt is set to 25, it should output it."0334

It was; but we will see that is not going to be the case; we are actually going to get a notice.0342

It is going to say that you have an undefined variable globalInt.0348

And that is because, within this function, globalInt has yet to be defined.0351

And within a function, it doesn't know about global variables.0354

The other side of that is that, in the global scope, you don't have access to variables defined within a function.0364

For example, we have a function here called localScope; it takes in one parameter, and it creates a variable called localInt=100.0375

Now, this is a local function variable, and what that means is: because it is defined within the function,0383

it is not available here in the outside script.0388

So, even if we were to (let's erase this) attempt to access this variable outside of the function, it wouldn't work,0391

even if we have already called the function.0409

For example, if we go ahead and call the function localScope, and just put a string that says Hello,0411

and now we call this function, it would get run; it would create this variable localInt=100.0427

And then, if we tried to echo that local variable out here, we are going to get an error, because it is defined within the function.0432

It has only function scope; it is not accessible outside the function.0439

So, when we run this, we are going to get another notice, and it is going to say undefined variable localInt on line 35.0443

We look at line 21 that is in our global scope, within the bigger script outside of the function; it doesn't know what localInt refers to.0453

At the same time (for example), we couldn't output param.0462

Even though, within the function, we could echo param that was passed in,0474

and that will work, because variables defined within a function are only available within that function,0479

so it knows about what param is; it is whatever value it was set to when the function was called (in this case, "Hello").0488

It will be able to echo it, but if we go down here and we try to echo it, it is not going to happen, because param only exists within the function.0494

For example, if we run the script, we will see that Hello is output, and then we get an error on line 36.0501

If we look back, Hello gets output because this echo statement knows what param is, because it has been defined within the function scope.0509

However, we get an error here, because we are trying to access the variable param that is only defined within the scope of the function.0518

That is the difference between global scope and local (function) scope.0525

Now, PHP does provide a way of being able to access global variables within functions, and function variables in the global scope.0533

And it does so by the keyword global.0541

What that does is: you can declare a variable within a function, and prepend it with this keyword global,0546

and that is saying that, any time you access that variable within that function, 0551

you are going to be referring to the global version of that variable.0555

And you need to do it by declaring it again with the global keyword first.0562

So, for example, if we look at a script called globalKeyword.php, we have a function defined called accessGlobal,0565

which we are going to get to in a second.0575

But what we do is define a global variable called globalInt=25, and then we echo that value.0577

We say, "in global scope, globalInt equals" the value of it, which is going to equal 25.0586

Because we are in the global scope, it knows about that variable.0591

Now, when we call this function, accessGlobal, and we go up here, and in the first line, we try to output globalInt,0595

it doesn't know what globalInt is, because it hasn't been defined within that local function scope yet, 0602

and it doesn't have access to global variables.0607

However, if we were to go ahead and redefine the variable by calling the variable name that we want to use0611

(that is a global variable) and prepending it with the keyword global, and then a space, 0619

then, when we try to use the variable globalInt within the function, it is going to know that we are referring to the global variable globalInt.0623

So, this echo statement, where we are trying to echo globalInt, will actually work,0631

because the function now knows that globalInt refers to this global access variable.0636

In addition, the other thing we can do is: because now globalInt within the function refers to a global variable,0642

we can change the value of the global variable within the function; we can set it equal to 0.0650

And so, after this function ends, when we try to output globalInt again, it is not going to be 25 anymore; it is going to be 0.0655

So, if we go ahead and run this script, you will see a couple of things.0663

First, we are going to see that the first output of globalInt equals 25; and that comes from this first statement here,0673

where we are in the global scope, and we are able to output this global integer.0680

Now, accessGlobal...the first thing it tries to do is access and output that globalInt, but it doesn't exist, 0685

because it's in the global scope, and it doesn't know about global scope variables.0692

So, we get this undefined variable on line 19; it says globalInt is undefined.0696

And when it tries to output it, it outputs a blank, because it has no value for it.0700

If we go back and look at line 19, this is where it is trying to access that global variable.0705

However, now that we have declared it here as a global variable, this echo statement actually works.0710

And so, when we look back at our script, we can see, the second statement in accessGlobal, after the declaration 0715

globalInt with the global keyword, it is going to output the value globalInt=25.0723

You also notice that, because globalInt refers to the global variable globalInt now (because of this keyword),0729

we can change the value of it; and so, when we change it to 0 here, and we access it again 0738

outside the function after the function has been called, its value is going to be updated.0743

And that is why you see the output here: in the global scope, globalInt is now equal to 0.0748

So now, we are going to talk about superglobals, which again, is a topic we have kind of talked about a little bit before, with the _GET and _SERVER variables.0757

Superglobals are predefined associative arrays by PHP that are always available in any scope.0764

They are available in global scope, and within function scope, which means that because they are global, you can use them0772

in the global scope of the script without a problem, because they are a global variable; but then, in a function, normally,0782

as we just saw, you need to specify with the keyword global in order to use a global variable.0787

Well, superglobals have the advantage of: you don't have to specify the global keyword before using them in a function,0792

like you would any other global variable.0801

Additionally, we are going to introduce a new superglobal called GLOBALS, interestingly enough.0805

And what that superglobal contains: it is an associative array that contains all of the global variables currently defined within your script.0811

And that allows you another way to access global variables within a function, because we know that we can't access global variables0821

within a function without using the global keyword.0829

However, we just learned that superglobals are available everywhere, and because the GLOBALS superglobal array0834

contains all of the global variables available, we can use that to access a global variable in the function.0843

I know it is a lot to soak in--a lot of "global" words being thrown around.0850

Essentially, the way that the GLOBALS array works is that the keys of the array are the identifiers, or the names, of all the current global variables.0854

And the values associated with those keys are just the current values of those global variables.0864

One other thing to mention is that constants, in a way, are kind of like superglobals, in that they are always available in all scopes.0871

They are available within function scopes; they are available within the global scope.0877

And like superglobals, you don't have to declare them within a function using a global keyword.0882

The way that they are not like superglobals is that they are not predefined by PHP.0889

So, let's go and take a look at a script that makes use of superglobals.0894

Here, we have a couple of functions at the top that we are going to talk about in a second.0900

Here we are at the beginning of our script; we are in the global scope--we are not inside a function.0906

And we are going to output the value of the superglobal variable _SERVER ['DOCUMENT_ROOT'].0911

And what that is going to show is that this superglobal is available within the global scope.0917

So, when we go ahead and run the script, the first output we should see is "in the global scope, _SERVER ['DOCUMENT_ROOT']=this."0922

Now, the next thing we do is call a function called useServer; and if we look up at the useServer function, it says,0935

"inside useServer," and it outputs the value of _SERVER ['DOCUMENT_ROOT'].0941

Now, because _SERVER is a superglobal variable, which is available in all scopes, we can access it within the function without using the global keyword.0945

And so, it should output its value; and when we look at the output (let's refresh it) we can see that the second output statement says,0955

"inside useServer, _SERVER ['DOCUMENT_ROOT'] equals" so-and-so.0962

And that shows you that you can access those superglobal variables within a function or in the global scope.0967

The other thing I want to demonstrate is the use of the GLOBALS superglobal that we have just talked about.0977

So, for example, if we define this global variable called globalInt, and we set it equal to 25,0983

and then we call the useGlobal function, if we look up at useGlobal, what it does is: it is trying to output the value of that globalInt variable.0989

Now, normally you have to declare the variable in the function, using the global keyword.1001

However, because all global variables are available within the global superarray, we can actually get access to it.1006

And the way you do that is: you access the GLOBALS superglobal array, and you specify the name GLOBALS, 1013

and then use as the key the name of the global variable that you want to output.1026

And this is using the complex curly bracket notation, and what this is saying is, 1030

"I want to get the value of the global variable called globalInt."1034

And because GLOBALS is available everywhere, because it is a superglobal, you shouldn't get an error here, 1040

and this should work, and it should output the value 25.1045

So, when we go and look at our script, we can see that it says "in the function useGlobal, this variable here, globalInt of the GLOBAL array, equals 25."1048

The other thing is to demonstrate about constants: we define a constant in the global scope called PI.1062

And then, we are going to try to output that constant within the global scope, and we are going to see that that works,1067

because constants have scope everywhere, which means they can be used within functions or within the global scope.1073

So, this is going to work; and then, when we call the function useConstant, and we look up useConstant,1084

it is going to try to output the constant defined in the global scope.1089

Because constants have scope everywhere, it is going to work, and we will have access to it.1093

And so, when we look at our output, we can see: in the global scope, constant PI equals this value;1098

in useConstant function, it has the same value, which shows that you can access that constant 1103

within the global scope or within local function scope.1108

We have introduced global variables, and now I just want to talk about some of the pitfalls of using global variables within functions.1115

In general, accessing global variables from within your functions should be avoided.1124

Instead, if you need to use the value of a global variable, you can pass it into the function as a parameter.1131

There are a couple of reasons for that--mainly that, by not accessing global variables within your functions,1137

you can increase the reusability, portability, and maintainability of your code.1145

And the reason for that is: first, by not using global variables, it eliminates a function's dependencies on a particular global variable.1151

For example, let's say you have a function named test, and we access the global variable...1161

maybe there is a global variable that exists that is just called a.1170

So, if we run that function test, and we use it to access a global variable a, as long as a is available as a global variable, that function is going to work.1174

Now, one of the reasons we create functions is to be able to reuse them; so let's say we put that function in a function library,1183

and we move it to our new web application.1189

In our new web application, maybe this variable a is no longer called a; it is called b.1191

Now, that function is not going to work anymore, because it is going to try to access the global variable a that doesn't exist.1198

So, when you include global variables within a function, you are creating dependencies on those global variables existing,1204

reducing the ability to reuse your code and to take it to other applications.1211

The other thing it does is: by not using global variables in functions, it reduces your debugging difficulties related to global variables being unexpectedly edited.1215

For example, if within a function we are using the global variable a, and we are doing some processing on a,1229

we expect a to be whatever the value is when the function started.1241

Now, let's say within our function, we go out and we call another function; let's say we called function test.1245

Maybe the test function is written by someone else, and it goes out and changes the value of a.1251

Now, if we were to go further down our script, and to try and access the a, and let's say we want to echo a,1260

we may have a problem, because we expect a to have the value that it had 1272

when we first defined the global variable, when we entered the function.1278

But another function, because it is a global variable, might change that variable; so it can have unintended consequences.1282

And that can cause a problem--that is going to make things harder to debug, because we have to go and look1289

at all the other code, to see if any of the other functions access those global variables.1295

In some cases, which we are going to see more of in the advanced class, using global variables within functions cannot be avoided.1305

And when that happens, you want to make sure that you document these functions extremely well,1313

because that lets any programmers that are going to be using this function know that there is a dependency on a global variable.1319

So, if they want to use that function, they have to make sure that those global variables exist.1324

I just quickly want to mention when variables can be defined.1332

You need to define (and we have kind of seen this implicitly, and haven't really talked about it explicitly) a variable in order to use it.1336

It must be defined before it can be used, and this includes (as we just saw) using global variables within a function.1343

If you want to access a global variable within a function, if you are not using the GLOBALS superglobal array,1350

you need to prepend it with the global keyword; and that is declaring the variable to be available for use in that function.1356

And as we saw when we tried to access a global variable from within a function without using the global keyword,1364

essentially, that variable hadn't been defined yet, and so that is how we saw that we got an error.1370

I just want to show one final example that puts all of this together that we have learned about.1378

We have learned about global variables; we have learned about local variables, which are created for functions.1382

We have formally defined what the superglobals are; we have talked about the scope, as they relate to constants.1388

And then, we are also going to show how scope applies to using variables within include files.1394

So, if we go and look at this script called scopeRecap...at the beginning of this page, it includes a library called testLIB.php.1400

It has a couple of test functions that we are going to use in the main script.1411

The first thing we do in the beginning of the script is: we define a global integer, and we define a global constant.1417

And then, we are going to show, through three echo statements, that you can access all of these variables within the global scope.1423

One you can directly access, using globalInt; the other one--because it is a global variable, 1431

it is maintained in the GLOBALS superglobal array, so you can access it this way, as well.1435

And because constants are available in all scopes, you will be able to output the constant variable.1441

If we go and look at scopeRecap, and load it, we can see at the beginning "global variable and constant access in the global scope."1447

And we can see that, in the global scope, we can access globalInt, and it is equal to 100.1458

We can access it by the GLOBALS array, and then, in the global scope, we also have access to the constant, because constants are declared.1463

Now, the other thing that we have done in this file is shown how scope is affected in include files.1471

And essentially, an include file is just considered a part of the PHP file it is included in.1477

So, any variables that are used in that are globally-scoped variables.1481

If we include this file called testInclude.php, which does the same echo statements we just did (it tries to echo the globalInt variable,1489

just directly accessing it, and tries to access it using the GLOBALS superglobal, and then tries to access it using the constant PI),1497

because it is included in line with that file, it has access to all of those global variables; it is not defined within a function,1505

and so, all of these should be able to output the correct value.1512

So, when we look at our file and output, we can see, in the include file, we have the same output as up here, globalInt=200.1516

We can access it by the GLOBALS array, and it equals the right value; and we can also access the constant PI.1523

The next sort of test we are going to do is trying to access global variables in a function where we don't use the global keyword.1533

We have defined a function in our testLIB called nonGlobalTest.1540

And what that says is: it tries to create a string that directly accesses this globalInt.1544

And we haven't used the global keyword within our function to define that variable, so globalInt, as far as the function is concerned, doesn't exist.1550

So, it is going to generate an error, and then we are just going to echo what the error message is.1557

And if we look at the page, we can see that global variable accessing nonGlobalTest...in that function, it generates an error1562

that says it's an undefined variable, globalInt.1568

So now, what we are going to do is define another function, called globalTest.1574

And what we are going to show is that you can access that global variable, as we had learned, if we declare it using the global keyword.1577

And so, once we have made this declaration here that globalInt refers to the global variable globalInt, we can directly use the variable.1585

Additionally, we are going to show that you can access the globalInt variable using the GLOBALS superarray,1594

and we are also going to show that, within a function, you can access constants, because constants have global scope.1602

In scopeRecap, if we look down and run globalTest, we can see that, in the function globalTest, 1608

globalInt=100 when we prepend it with the global keyword, which means it is giving us access to the global variable.1618

We can access the variable using the GLOBALS superarray, and we can also see that the constant is available within the function.1627

We have also defined a function called localTest, which has a parameter that gets passed in, and it defines a local variable.1635

And in the function, it outputs the value of the parameter passed in, and it outputs the value of the local variable.1642

And this is going to show that, because localVar is defined within this function, and param is defined as part of the function's parameter list,1648

they are going to be available within that function, so these outputs should work.1656

So, in scopeRecap, when we call localTest with this string param value, we can see that, in localTest, localVar=local,1659

which is the value we had set it to within the function.1673

And we can see that param has the value 'param value,' which is passed in.1676

Now, just to show the other side of it, in the global scope, now, we are going to try to output 1681

the variables that were defined in the function: the localVar variable, 1690

and then also the param variable, which is defined as part of the function.1695

And you can see here, we have error suppression operators, because you are going to generate a warning, because those variables aren't available.1699

It is just going to output them, and it is going to say these variables don't exist within the scope.1705

And as you can see, it says "undefined variable localVar," "undefined variable param."1710

So, this is sort of an example that you can look at and see all of the different interactions--1714

how scope interacts in all sorts of different ways when using functions, when using constants, when using superglobals,1719

being able to access function variables outside of functions, being able to access variables within include files, and so forth.1726

It kind of sums everything up.1733

So, I'll just quickly mention this: it doesn't fall under the function of variable scope, but because we are talking about scope,1737

I want to mention that functions have a scope as well.1742

A function has a name, which is an identifier; and as we know with variables, 1747

variable scope defines where that identifier has meaning--where you can use that identifier.1751

Well, functions in general have global scope, just like constants and superglobals; they are available everywhere.1756

So, you can call a function within the global part of your script, or you can call it within another function.1760

It also can be called within any include files that you include within your main file.1766

And the main thing about it is: because they have global scope, they never need to be defined with the keyword global.1776

For today's homework challenge, I want you to get a little practice with trying to understand this scope concept that we have introduced.1783

I would like you to create a script that defines a variable and a constant.1790

And when you define them in the main script, that means that those variables have global scope.1794

And then, I want you to go ahead and output them, to show that within the script, you have access to those variables.1800

Then, define a function that takes one parameter and also defines one local variable within its function body.1806

And then, what I want you to do is, within the function, also try to output the global variable that you defined in step 1,1815

without using the global keyword, and without using the GLOBALS array.1824

And what you should see is: you should get an error that you are not able to access that.1828

Then, go ahead and use both the global keyword and the GLOBALS superglobal to access that global variable from within the function,1833

to give you practice with using the global keyword and the superglobals array.1842

Also, try outputting the constant that you defined in your main script from within the function,1849

to show that constants have global scope, and they are available within the function, as well.1855

Then, because the function has a parameter and a locally defined variable, 1861

I want you to output both the parameter and that locally defined variable from within the function.1864

That is going to show you that these function variables, including the parameter, have scope within the function.1870

And then, try outputting the function parameter and the variable that you created locally within the function outside the function,1875

after the function has been called within global scope.1882

And you will see that you should get an error, because those variables have local function scope and are not available in the global scope.1884

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1892

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be continuing work on our web application, incorporating what we learned in our last lesson about variable scope.0004

In today's lesson, we are going to go over a new version of the web application, which is going to be version 11.0.0014

And as a part of that, we are going to be adding four new functions to our function libraries.0019

The first one is called processGetVar, which is used to process GET variables.0026

We are going to have an email comment function, in which we are going to extract the part of our contactUs.php script0032

that does the emailing of the comments.0039

We are going to add a function that is going to be used to output item links, and that is going to be used in viewCart.php.0043

And then, we are also going to create a function called calcCartTotal, which is going to be used to calculate our Shopping Cart total.0049

In version 11.0, as mentioned, we are going to be adding these four new functions.0059

What they are going to do is promote us reusing code, as well as aiding in the separation of our PHP and HTML,0063

which, as we began talking about in User-Defined Functions, is an important feature of your web application.0073

These are the files that we are going to be editing, down here.0079

So note, we are going to be editing both outputLIB.php and utilLIB.php, which are function libraries.0082

And then, the other pages that we are going to be editing make use of these two functions that we have created,0090

except for config.php, which--the only reason it is listed here is because we are updating a new version number for that file.0096

The first function that we are going to be creating for this version of the web application is called processGetVar.0104

And it is going to be in utilLIB.php, and it is a utility function that puts common code used on all of our pages that use GET variables0111

into a function, so that we can reuse it in multiple spots.0120

The three pages that we have that use GET variables are checkout.php, contactUs.php, and item.php.0124

And what this function is going to demonstrate from our last lesson is the use of superglobals within local function scope.0131

And as we learned before, there are two scopes in PHP: there is global scope and local function scope.0140

Let's take a look at using this new function.0145

First, if we go, for example, and look at...this is version 10.0 of checkout.php, what we can see here at the beginning is:0152

when we process all of our GET variables, here we have action and cartItems; there is also customerData and orderTotal.0161

And if we look, we can see that basically the same code is being reused over and over.0169

We are using a ternary operator to decide whether to set action equal to a variable specified or null,0174

which depends on whether the GET variable is set or not.0180

And as you see, between this line here (the one for cartItems), the one for customerData, and orderTotal, the only difference in the code0184

is what the variable name is that is included within the square brackets for the GET array.0192

So, what we can do is "parametize" that and create a function that is just going to 0202

accept the name of the GET variable that we want to process, and it is going to perform the same action.0207

So, if we go and look at utilLIB.php, down at the bottom, the function processGetVar is created.0213

And what it does is: you can see here, it's a simple one-line function, and what it does is the same operation that we saw on the last page0224

(I'll move it up a little bit) in that, first of all, it accepts one parameter, variableName, 0233

which is the name of the GET parameter that we want to process.0241

And then, what we do is: we test to see if that variable was set in the GET superglobal.0245

And if it is, we return the value of that GET variable; and if not, we return the value of null.0253

So, we are performing the same operation, but we are doing it within one function.0260

And as you will notice, we are accessing the GET superglobal variable; so this is an example of accessing superglobals within the local function scope.0264

And as you can see here, in the description that I have given of how the function works, along with parameters and return values,0274

I also typically like to include a section that mentions any global dependencies.0281

And so here, I just mention that this function depends on the global variable, and the superglobal variable, the _GET.0285

If we go back and look...this is checkout.php from version 10.0, and if we look at version 11.0, 0295

we can see that all of those ternary operations were replaced with a call to the processGetVar function.0305

And we specified, as the argument to that function, the name of the GET variable which we want to process.0312

This is going to perform the same action; it is going to test if action exists.0319

If it does, it is going to set the short version of our GET variable action to the value that was provided, or input, to the page.0323

If not, it is going to set it equal to null.0334

And as you can see, we have reused the same function down here in all of these other spots.0336

And so, it has actually kind of cleaned up our code a little bit, in that 1) it looks a little neater, in that we have a simple function call,0341

versus a long ternary operator; but also, again, the advantage of doing this and of using it in a function is that we get code reuse.0348

Whereas before, we had 4 different variables that we used a ternary operator to set the value of--that is 4 chances0357

where we could make mistakes in writing that ternary operation--here the only mistake we could make, because we are using the function,0367

is mistyping the name of the function's argument.0376

The other spots...if we look back at the LIB...we could mess up putting the name of the variable here, or the name of the variable here.0381

So, we are kind of reducing that at the same time that we are cleaning up our code.0389

The next function that we are going to create for this version of the web application is called emailComments.0397

What it is going to do is remove from contactUs.php our large section of PHP code that we use 0403

to process the information that was input from the Contact Us form, in order to send out an email.0410

The function is going to be defined in utilLIB.php, and what it is going to do is demonstrate the use of constants.0418

In this case, we are going to be using the email constants, which we had defined previously in config.php.0424

And it is going to show how to use constants within local function scope.0430

Let's take a look at the old version of contactUs.php; this is version 10.0, and we scroll down the page into the final HTML Output section,0435

which we reach, if you remember, when the action provided to this form is equal to contactUs.0451

And you can see here that we create short variable names for the information provided by our contactInfo, which is a GET variable.0459

If we go back and look at the top, you can see that, in this contactInfo's setup here at the beginning of the page, 0468

we set it up as a short variable for the GET variable contactInfo.0479

These are, again, shorter variables that we can use below in creating the email.0487

We can see here where we build up the email message; we create the email header; and here is where we send out the email message.0493

And then, we output a message to the user, saying whether the email sending was successful or not.0502

What we can do is extract all of this PHP code in this section here--extract it out into a function 0508

and replace it with a single function call that is going to perform the same functionality.0516

If we look at contactUs.php version 11, and we scroll down to that same section in the code,0520

now that whole section of code that was related to sending the email has been updated to one line 0528

that is the function call to emailComments.0535

And what it does is passes this GET variable, contactInfo, to the function, so that it can go ahead and build up an email, and then send it out.0538

Now, emailComments is going to return a boolean value, indicating whether the email was successfully sent or not.0547

And we can use that value, just as before, to output whether we are going to output a message 0552

that says "Thank you for your comments" or "There was an error in sending us your comments."0558

One thing to note, too, is that, in version 11.0, at the beginning here, we have also made use 0563

of our processGetVar function for this page, as well, for both the contactInfo and action GET variables.0568

If we go and look at utilLIB.php, and we go to the emailComments function, which is listed here, you can see, the same code0579

that we had in the contactUs page is now moved into this function.0592

We are creating short variables for the contact information data, which is useful in building up the email message.0598

Here is a section where we built up the email message that we are going to send.0605

Here we create the email header, and then, as before, we are going to call the mail function provided by PHP,0608

using our two constants that we defined in config.php.0618

So, this is an example of using constants, which have global scope, within the local function scope.0622

And as you will notice, we haven't had to declare them with the global keyword or use the GLOBALS superglobal array,0629

and that is because that is how constants work, as far as scope is concerned.0635

So, we send out the email, using the mail function, just as before; and what we do is suppress the error,0640

because if an error occurs, it is going to return false; and we simply return the return value of mail,0648

which is going to be true or false, depending on whether the mail was able to be successfully sent to the outgoing mail server.0653

And again, just a reminder from when we talked about the mail function before:0660

just because the mail function in PHP returns true, it doesn't necessarily guarantee that the message was going to be delivered.0663

But it does let you know that it was successfully passed along to the outgoing mail server, and that is as far as that function works.0670

The next function that we are going to create is called outputItemLink.0681

And this is something that is used in the viewCart.php page to output links to each of the different items' pages--their product information pages.0686

And what we are going to use this function for is to take common code that is included in viewCart.php,0697

move it out into a function, and make our code look a little bit cleaner.0702

If we go and look at viewCart (and this is version 11.0), we can see here that we have a link, and this is what is our outputItemLink function.0707

It is going to output this image, the small image of our item, which is a link to the item page.0719

If we click on it, it goes to the item page.0727

We also are going to be creating this text link that is the name of the item, and then when you click on that, it goes to the item page.0730

And as you can see here, we have three different items, and so this is a common function that is being performed.0738

We are outputting a link that contains an image and a name of the item.0743

And here, we do it three different times; so we are going to put that in a function and make use of it.0748

If we go and look at our previous version of viewCart.php, and scroll down the page, we can see here that, as before,0754

we have sections where we list the different items' information.0764

For example, we list item-1001's info, item-1002's info, and so forth.0769

And we have the three different columns of our table: one is the link to the item page, one is the price, and one is the quantity.0773

Well, here is the code that we had before in order to output the item link.0780

We defined the item ID of variable; we loaded the item from the catalog and created some short names to use in outputting our link.0785

And then, here is a section where we output the link to the items page.0794

One is a link that includes an image tag, so the image becomes a link.0803

And then, we also have a span here that includes a text link, that has the name of the item.0808

And the reason we have included them as separate links is just for formatting purposes.0814

But what you can see is: if we look down at, for example, the row for item-1002, you can see that, essentially, this is exactly the same code as before.0820

The only difference is that currentItemID is equal to 1002.0832

So, any time that we have the same code that we are using over and over again, 0837

we want to take advantage of being able to put it in on spot, and therefore only having to change it in one spot.0840

So, we are going to put it into a function.0844

What we are going to do is: we are going to create a function called outputItemLink.php.0847

This is going to be in the outputLIB.php function library.0855

And the reason for that, again, is that we put all of our functions that output HTML into the same function library,0858

and for this web application, it's outputLIB.php.0866

So here, we can see the new function that we have created, outputItemLink.0869

It takes one function parameter, which is the item ID of the item that we want to look up and output the link for.0875

And what you can see here is: basically, it is the same code, slightly modified, that we had within the actual viewCart page.0889

But as mentioned, we used this code three times, so we are going to go ahead and put it in a function,0899

so we can just call the function three times, as opposed to actually having to write this code three times within our file.0903

Not only is it going to increase the maintainability, because we have less chances for mistakes,0908

but also, it is going to, as we will see, make our code look a little bit cleaner by getting rid of PHP code contained within an HTML file.0913

One important thing to notice is that this function makes use of the GLOBALS superglobal array.0922

And it does that in order to load the item catalog, which, if you remember, is contained in our catalog.php file.0928

It is a global variable, and so, in order to access global variables within local function scope (and this is a function),0936

we need to either use the global keyword or access them by the GLOBALS superglobal.0944

And here, that is what we have chosen to do; we could have also done it with the global keyword, as well.0950

And so, this function demonstrates using global variables within local function scope.0955

It also, down here, demonstrates, again, using constants within local function scope; 0960

and here, you can see, we are using the IMAGE_DIR constant when we output our image tag.0965

And again, constants have a global scope, and they don't need to be prefaced with the global keyword when they are being used within a function.0971

So, this is the same code that we had within the file, but we have included it in a function.0978

Now, if we go and look at viewCart 11.0, and we go down and look at each of the rows for all of our different items,0983

here we have, for item-1001, significantly reduced the amount of PHP code within our HTML file.0994

Here, we have just defined currentItemID, as before, which is 1001.1004

And now, for the column where we would output the item link, which is the image and the name link to the item's page,1009

we simply have a function call that we echo, and we pass it the current item ID, which is 1001.1017

And as we know from just looking at the function outputItemLink, we can look up the global variable using the GLOBALS superarray,1021

and be able to load all of that item's information.1030

And then, here we go ahead and output the price, and our text box that receives the quantity of items the user desires.1032

Now, one thing to note is that the price column changed a little bit, because in our previous version, if you look,1041

because we actually loaded the item from the item catalog within viewCart.php,1049

we went ahead and created a short variable called curPrice that represents the current item's price.1055

And so, when we went down here to our column for outputting the item's price, we just referenced that short variable.1062

Well, in our new viewCart.php, we don't load the item here; we load it within this outputItemLink function.1070

So, we have to load that price manually here; and so here, we are, again, looking up (in itemCatalog) the current item,1076

which has the item ID, curItemID; and then we are getting the price value out of that array for that particular item.1088

And then, we are outputting it; and as you can see, for item-1002, we have the same thing.1100

We have replaced this with outputItemLink; for 1003, we have replaced the whole section with outputItemLink.1105

So, we go back up to item-1001; there is the start of item-1001.1110

And if we look at the same one on version 10.0, here is the code and HTML for outputting the link to item-1001.1122

As you can see here, we have a lot of PHP code contained within this first td tag.1133

Now, it is simply replaced with this one function call, so that really neatens up our file, and again, separates our HTML and PHP,1141

which is good, because if we have (for example) developers that work on PHP specifically, and developers 1148

that usually just work on the HTML portion of the site, it allows the HTML developers 1153

to work on the page without having to be involved with the PHP code itself.1159

The last function that we are going to add to this version is called calcCartTotal.1168

And what that is going to do is take the calculation operations that we did at the top of checkout.php,1172

when calculating the Shopping Cart total, and move them out into the function.1181

And again, the reason for this is to remove as much PHP code as we can from our HTML/PHP files that eventually get output to the user.1184

The function is going to be defined in our utility library, called utilLIB.php.1196

And what it is going to do is access global variables; it is going to access the item catalog that is defined globally in catalog.php,1201

which we include in all of our pages.1209

But it is going to access it differently: as opposed to using the GLOBALS superglobal, like we did in outputItemLink to access it,1212

or even using the global keyword, we are going to pass the item catalog itself into this calcCartTotal function.1219

And what that does is: it is going to reduce this function's dependency on the global variables.1234

So now, this function, in a way, becomes more of a standalone function that can be reused in other spots,1242

because the function will always be able to work in a way, because it is always going to have an item catalog passed to it.1246

So, it will always have an item catalog to work with.1251

If we directly access the global item catalog variable from within the function, using GLOBALS superglobal or the global keyword,1254

then we become dependent on the fact that that function is always going to have to work in a PHP web application 1263

where that global variable is defined.1269

So, this is going to improve our function's reusability.1271

Let's go take a look at our old checkout.php page.1277

If we look at the top section, where we calculate the total of our cart, we have a bunch of arithmetic operations here1284

where we multiply each item's price times the quantity the user submitted, and cumulatively add it up.1296

Then, we multiply it times the sales tax rate to get our final total including sales tax, and then round it off.1304

Well, what we can do is remove all of this code right here out into a PHP function that we are creating called calcCartTotal.1311

And we are going to reduce this all to a simple function call.1320

If we look at version 11.0 of checkout.php, whereas we had all of those calculations before, right here in this section,1324

now it has become a single function call.1338

It is a function call to calcCartTotal; it is going to return the total calculated, which we are going to store 1341

in the same variable that we had before, curTotal for current total.1345

calcCartTotal is going to take in two parameters: the first one is cartItems, and cartItems is (if we look at the top) a GET variable.1350

that is passed to the form from viewCart.php, and is an associative array that lists the item ID as the key,1363

and then the quantity selected by the user as the value, of the array.1372

We are going to pass that GET data on to our function.1375

And then, we are also going to pass along itemCatalog; and because we are in global scope right now1381

(we are not within a function in this script), itemCatalog is accessible.1387

It is a global variable, which we can find in config.php, and it has global scope.1391

So, we have access to it, so we are going to pass that variable directly to the function, so that it doesn't need to use1395

the GLOBALS superglobal or the global keyword in order to look up the item's price within the item catalog.1401

If we go and take a look at utilLIB.php, and we look at the function we have created called calcCartTotal,1410

here you can see, basically, it has the same code that we had used before, and we have just put it into a function.1418

And what it does is uses the item catalog that was passed into the function, as opposed to directly accessed using the global keyword,1427

to look up each of the items' prices, and then it multiplies it times the quantity of the item that was selected by the user,1437

which is the value associated with the key that is the item ID of the item you are interested in, in cartItems.1446

Again, cartItems is the GET variable that was passed to checkout.php from viewCart.php.1458

So, we perform the same calculations and cumulatively add up the total.1466

Here, we do have a little bit of global dependence, in that we are accessing the sales rate constant, which we had defined in config.php.1471

So, we go ahead and add the sales tax to the total, and then we return the total, rounded to two decimal places.1482

We are essentially performing the same things as before.1488

And as you can see up here, for global dependencies listed, we have a global dependency on the constant sales tax rate.1491

And actually, if we go ahead and look in another file, outputLIB.php, and look at our outputLink item link function,1499

there are actually two global dependencies; one is on the constant IMAGE_DIR, 1515

and one is on requiring that this item catalog, global variable, be available.1518

So, in this new function that we have created, we don't have that dependency any longer--which, in general, is a good thing.1526

And so, here, once again: what calcTotal does is return the rounded-off value.1539

And then, when we go and look back at checkout.php, it returns that value to curTotal,1546

which we can use throughout the rest of the page, to output the total as needed.1551

For today's homework challenge (it is typical of our web application lessons), I just want to make sure 1559

that you understand working with local function scope and global scope, 1564

and understanding how, within our functions, we can access superglobals, constants, and global variables,1571

and the different ways that we do that.1578

Superglobals are always available; constants are always available without having to use the global keyword.1580

And then, any other global variables defined in our main script can be accessed by the global keyword or the GLOBALS superglobal.1585

Additionally, just note how, for item, outputItemLink, and calcCartTotal, we essentially are accessing global variables in different ways.1594

In this one, we are accessing it directly, using the GLOBALS superglobal array.1605

And here, we are reducing the dependency on the global variable by passing the catalog itself into the function,1610

so it has direct access to it without having to use the GLOBALS superglobal array.1620

The other thing is just to be sure that you understand, for step 3 here, how separating out the PHP code into our 4 different functions1629

is going to promote code reuse, because, as we saw several times, we are taking similar sections of code and "parametizing" it,1636

putting it into one function that we can call over and over.1645

So, if there are any problems with that code, we can edit it in one spot.1648

As we will see as our web application builds up, that is also a good thing, because then, maybe, if we change 1652

how we want to (for example) process a GET variable, we only have to do that in one location,1656

as opposed to going through and doing it in every location where we process a GET variable.1661

And also, understand how doing functions allows for the separation of PHP and HTML,1666

where we are taking large sections of PHP in what are essentially files that are output to the user (they are .php files that contain1673

a mixture of PHP and HTML), taking the PHP out, and moving it into a function file.1681

And it cleans up our output pages that maybe an HTML developer would work with.1688

So, in the end, this ends up making a more flexible and easier-to-maintain web application.1694

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1702

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be introducing the topic of optional function parameters.0004

Specifically, we are going to be talking about optional function parameters, describing what they are0011

and how they are defined within a function, as well as how to call functions that have optional parameters as an option.0017

As mentioned, when we define user-defined functions in PHP, they can have optional parameters.0030

And what that means is: the user can choose, when they call that function, whether to provide an argument for a particular optional parameter.0036

All of the functions we have defined so far have required parameters, which means,0044

when you call the function, if it has two parameters that it takes, you have to provide two arguments to that function.0047

The way you define an optional parameter is like this.0054

Here, we have a function, just called test, and an optional parameter is set up by...you define the name that you want to use0058

for the optional parameter, and then you give it a default value.0067

When you define a function in this way, any parameters that are defined without default values,0071

such as req for required parameter in this case, are going to be required parameters.0078

Any ones that you define with default values are going to be optional parameters.0083

Now, what that means is that, when you are accessing (for example), within the body of your function, these different variables,0090

these parameter variables, when you access a required variable, you will just access it as usual.0098

When you access...for example, let's say we want to output the optional parameter that a user passed in...0105

If the user passed in an optional parameter, then optional is going to be set to that value.0110

So, if the user called this function, for example, then required is going to be set to 5, and the optional parameter is going to be set to value 5, as well.0116

If we had just called test with one parameter (in this case, 5), then required is going to be set to 5.0133

And then, any time, for example, let's say we want to echo the optional parameter in our function--any time optional is accessed--0141

in this case, because we didn't provide it with a value, the default value of 1 is going to be used.0155

So, in this case, it would output the value 1, because on this call to test, we did not provide the optional parameter.0160

One thing to note is that the default value could be set (I'll clean this up a little bit) within the function definition.0168

These values must be constant values, and they also must be of the following data types.0178

They can be scalar constant values, which can be constants or actual literal values (such as, for example, the literal number 1).0184

They can be any of the scalar types; they can be an array, as long as the array is filled with literal values;0194

or the array may have constant values in it, as well.0200

Or, they can be set to the default value null.0203

Let's take a look at a script here called optionalParameters.php.0210

Here, we are going to define a function called optional that is going to have two parameters.0215

It is going to have on that is a required parameter and one that is an optional parameter.0220

The required parameter is going to be called required; the optional parameter is going to be named optional.0224

And so, what this function does, essentially, is just outputs the two values 0229

of the required parameter and the optional parameter that may have been passed to the function.0234

What I am going to do is go ahead and fill in here the function definition that shows how optional parameters are created.0239

With required, we don't set a default value, because it is a required parameter.0245

However, with our second parameter, named optional--it is an optional parameter, so we have to give it a default value0249

in order to signify that it is an optional parameter.0258

In this case, we are going to set the default value for optional equal to 1.0267

And then, down here, in this section, I have a little message saying that we are only providing the required argument.0271

So then, now that we have defined this function, if we go ahead and call optional and provide it (for example) with the required parameter0276

(we'll just pass in the value of 5), what is going to happen is: required is going to be set to 5, and optional,0287

because no value was passed in, is going to be set to 1.0294

So, if we save this and go ahead and view it in our browser, we can see that required is set to 5; optional is set to 1.0297

And that is because optional was not provided when we called the function.0305

Now, if we go back here, I have a second statement that says we are going to provide both the required and optional parameters.0311

We call optional again; in this case, we provide the same required parameter; but this time, let's say, we provide the value 12 for the optional parameter.0318

When we run the function, required is going to get set to 5; and then optional, instead of being equal to 1, is going to get set to 12.0326

So, we should have the output that shows 5 and 12.0332

And if we save this and go ahead and reload the page, we can see here, in this second statement,0336

that required was set to 5, and the optional value was actually set to 12.0343

And as mentioned, these parameter default values for optional parameters must be constant functions.0351

So, you could include a constant in here; there is a constant we haven't defined.0360

But if you try to do something like (for example) make a function call--for example, to time,0366

what is going to happen is: you are going to get a parse error when you try to run the code.0374

If we reload the page, it is going to say "unexpected parentheses," and what that is telling you is that you can have only constant values0379

and nothing that does any sort of function calls or computations, or anything like that.0392

Alternatively, we could have a value null, as we had mentioned.0397

In this case, if we go ahead and refresh our script, we can see that optional here outputs nothing, because the string value of null is the empty string.0402

There are a couple more things to mention about optional parameters, and they have to do with 0417

when functions have multiple optional parameters, which is completely allowed.0421

You can have as many optional parameters to a function as you require.0426

And the thing to note is that when you call a function requiring optional parameters, arguments do not need to be provided for all of the optional parameters.0430

That is why they are called optional parameters.0437

However, there are some rules that you need to follow when calling functions with optional parameters.0440

First of all, if (let's say) a function takes one required parameter and three optional parameters, if you want to only provide0447

a value for that third optional parameter, there is a special way that you have to call the function, which we are going to show in a second.0456

And what it does is says that, for any other optional parameters that are previously defined in the function, you have to provide them at least some value.0463

And then, let's say for a function that has three optional parameters and one required parameter, you only want to provide the first optional parameter.0473

Well, you can actually leave off the second two without any problems.0482

Let's go take a look at another script called moreOptionalParameters.php.0486

Here, we have a function that is going to accept one required parameter and three optional parameters.0491

I'll put these on separate lines to make it look neater.0501

And I am just going to set these to some string default values.0511

This right here is our parameter list for this function; it contains one required parameter and three optional parameters,0531

which you can identify by the equal sign that is assigning a default value to those optional parameters.0543

So, if we call this function with just the required parameter, it is going to output the value of the required parameter that we passed in,0552

and then output these three default values.0559

If we go ahead and call this function with just the required parameter--just call it required value as a string--and we go ahead and 0563

load this page in our browser, you can see that it outputs the required value that we supplied.0578

And then, because we didn't supply values for the optional parameters 1, 2, or 3, this outputs their default values.0589

Now, let's say we just want to, for example, provide the first and third optional parameter.0598

Well, there is a way to do that in PHP.0603

This messages is just outputting a little HTML comment, saying we are just providing required and third optional argument0606

(actually, for this example, we are just going to provide the required and only the third optional argument).0615

What that means is: in order to do that, because we want to provide the third optional argument only, and not the first or the second,0621

in order to do that, we have to provide values for both of those optional parameters.0629

If, for example, let's say we just set the required parameter, and we just want to set the third optional parameter,0636

and we say param3 value, what is going to happen is: because this is listed as the second parameter, 0645

even though we want it to set the parameter optional3, because it is provided second, 0659

it is actually going to set the value of the optional1 parameter.0666

So, what we have to do is provide some sort of value for those other optional parameters.0670

In this case, we supply a value null; so, what that is going to do, when we call this function, is set required equal to this string required value.0679

It is going to set the value of parameter optional1 and parameter optional2 both to the values of null.0692

And when we try to output them, it is going to output the empty string, because null converted to a string is the empty string.0699

And then, we have set parameter 3 to this string value here, so when optional3 is output, that string will be output.0705

So, if we go ahead and save this and reload it in the browser, in our new section down here that says0712

we are just providing the required and third optional arguments, we can see that the third value was output.0718

optional1 and 2 were not output, because they had to be provided a value, and we provided them the value null; and parameter 3 was output.0724

Now, the other thing that we can do is: if we only want to provide (for example) the first two optional parameters,0736

along with the required one, we don't have to do anything special and provide a value for this third optional value.0746

Whereas here, because we wanted to provide the third value, we had to provide sample values for the other two optional parameters,0752

if you are providing optional parameters that are to the left of other optional parameters (for examp