The Wonderful PHP if Statement

Video loading...

Join Drupalize.Me to watch this video

Join today and gain instant access to our entire video library.

Log in Sign up
  • 0:02
    The Wonderful PHP if Statement with Leanna Pehlam
  • 0:08
    LEANNA PELHAM: Let's start to make our code smarter.
  • 0:13
    Modify your pets.json file and remove
  • 0:15
    the age key from just one of the pets.
  • 0:20
    When we refresh, it doesn't fail nicely.
  • 0:23
    It gives us a big, ugly warning.
  • 0:27
    Let's dump the queue pet variable inside the loop
  • 0:29
    to see what's going on.
  • 0:36
    Each pet is an associative array, but as you probably suspected,
  • 0:39
    Pico de Gato is missing her age key.
Loading ...

The Wonderful PHP if Statement

Loading...

When you reference a key on an array that doesn't exist, PHP will complain. Instead, let's code defensively. In other words, if we know that it's possible that the age key might be missing, we should check for it and only print the age if it's there. We need to add some logic. To do this, we'll finally meet the wonderful and super-common if statement. Like foreach, it's a language construct, and is one of those things that uses curly braces to surround a block of code. Where foreach accepts an array and executes the code between its curly braces one time for each item, if accepts a Boolean value — in other words: true or false. If what you pass it is true, it executes the code between its curly braces. In this lesson we'll use the if and else statements, and see how to combine our conditions, along with a variety of operators, to get exactly what we need.

Downloads: 
Log in or sign up to download companion files.

Additional resources:
There are no resources for this video. If you believe there should be, please contact us.