php has many ways to perform actions conditionally but the simplest is one many developers don't use because they've never noticed it. it doesn't even show up in the most popular online courses in php. we will talk about the others, of course. but this is the most basic of conditional ideas to start and only requires a few characters.
imagine you have a user giving you a number but it has to be less than 100 for you to do anything with it.
$input = 55;
$input < 100 && print_r($input . " is a great number!");
returns 55 is a great number!.
how does it work? the && operator stops as soon as anything in that command is untrue. so, if $input is not less than 100, it doesn't do anything else from the rest of the line to the ;. if it is less than 100, though, it keeps going.
you can use this to work with strings, too. before we get there, though, it's important to know the difference between =, == and ===. when you use a single equals sign, that means you are setting whatever is on the left to be the same as whatever is on the right. if you use two equals signs, you are checking to see if the left and right are equivalent. if you use three equals signs, you are checking to see if the left and right are absolutely equal. we will talk about the difference between equivalent and equal a bit later but it's usually a good idea to use equivalent unless there's a specific reason to want to be more intensive in checking.
$input = "hello";
$input == "hello" && $input .= " everybody!";
print_r($input);
returns hello everybody!. this introduces a very useful shorthand, .=. you have already learned that . is how we combine two strings and that = is how we set the left equal to the right. when we combine them, we take whatever is already on the left and combine it with whatever is on the right.
$input .= "some text"; is the same as $input = $input . "some text";.
sometimes, it is necessary to do something different depending on the status of an input. if we take the same example...
$input = 55;
$input < 100 ? print_r($input . " is a great number!") : print_r($input . " is a terrible number!");
still returns 55 is a great number!. if we change the first line, though...
$input = 237;
$input < 100 ? print_r($input . " is a great number!") : print_r($input . " is a terrible number!");
returns 237 is a terrible number!. the ? operator asks a simple question -- is whatever is on its left true or false? if it's true, do the first action on the right. if it's false, do the second action. these actions are separated by :. we can also use this with = to set variables.
$input = 8;
$output = $input < 10 ? "small" : "large;
returns small. the variable $output is set to the first option because $input < 10 is true.
it is a good idea to make as many of your actions as you can simple -- just one task at a time. if you need to do more than one task based on a value being true or false, however, you can use another type of check -- if and else. that brings us to the difference between the types of brackets in php.
you have already seen (), round brackets, used to pass information to a function. these same brackets are used to group things together. [], square brackets, are used to pass a name or number of where something is. for example, if you have an array called $fruits, $fruits["banana"] refers to the banana member of that array. {}, curly brackets, are used to separate a block of code and assign it to a particular task. that is what we will be using now for our conditional actions.
$input = 73;
if ($input < 100) {
print_r($input . " is less than 100");
} else {
print_r($input . " is at least 100");
}
returns 73 is less than 100. of course, you are probably thinking this is a needlessly-complicated way to do this...
$input = 73;
$input > 100 ? print_r($input . " is less than 100") : print_r($input . " is at least 100");
and you would be correct. what is important about this new syntax, however, is that we can use it to do more than one thing at a time.
$input = 204;
if ($input < 100) {
print_r($input . " is less than 100");
$output = "small numbers are fun";
} else {
print_r($input . " is at least 100");
$output = "large numbers are sad";
}
print_r("\n" . $output);
returns...
204 is at least 100
large numbers are sad
remember, if we don't add the \n for a new line, the "l" of "large" will come immediately after the "0" of "100".
when you have to perform more than one action at a time, you have no choice but to use the explicit if and else syntax instead of the simpler && or ? and :. it is common to see a mixture of these types in a php program.
note, the else part is optional and only needs to be included if there is an action to be performed in the "not true" case.
one of the most useful characters in php is !. you can put it in front of anything to mean "not". if we take the first example...
$input = 55;
!($input < 100) && print_r($input . " is a great number!");
returns nothing because, while $input < 100 is true, the ! reverses it. if we want to make sure a number is not 0, for example, but it can be anything else for division, this is a simple check.
$numerator = 12;
$denominator = 4;
$result = !($denominator == 0) ? $numerator / $denominator : "oops!";
print_r($result);
returns 3. if we change $denominator to 0, it returns oops!.
we can also use the ! inside our conditional.
$numerator = 27;
$denominator = 3;
$result = $denominator != 0 ? $numerator / $denominator : "oops!";
print_r($result);
returns 9.
you have already seen php doing math so the first set of operators should come as no surprise.
| php | action |
|---|---|
$a + $b |
adds $a and $b |
$a - $b |
subtracts $b from $a |
$a * $b |
multiplies $a and $b |
$a / $b |
divides $a by $b |
$a ** $b |
raises $a to the exponent $b |
$a % $b |
gives the remainder of $a / $b |
if the last one appears out of place, it is generally used as a test to see if a number is a factor of another. if $a % $b is 0, $a is divisible by $b. if you are breaking a list into pages, $a % $b is the number of items on the last page if there is a partial page to be displayed.
you can also use + and - the same way they are used in standard arithmetic.
$a = 3;
$b = +$a; // 3
$c = -$a; // -3
you have already seen assigning and adding to the variable on the left but there are other operators to complete that set.
| php | action |
|---|---|
$a = $b |
sets $a to whatever $b already is |
$a .= $b |
adds $b to the end of $a |
$a += $b |
sets $a to $a + $b |
$a -= $b |
sets $a to $a - $b |
$a *= $b |
sets $a to $a * $b |
$a /= $b |
sets $a to $a / $b |
$a %= $b |
sets $a to $a % $b |
$x++ |
returns the value of $x then sets $x to $x + 1 |
$x-- |
returns the value of $x then sets $x to $x - 1 |
++$x |
sets $x to $x + 1 then returns the value of $x |
--$x |
sets $x to $x - 1 then returns the value of $x |
the action for $a = $b might sound a little strange but it's important to remember that it sets $a to whatever $b is at that moment, not permanently. that means $b can change but $a will remain the same.
$b = 10; // $b is 10
$a = $b; // $a is 10
$b += 5; // $b is 15 but $a is still 10
php has operators for comparing values. you have already seen some of them.
| php | action |
|---|---|
$a == $b |
are $a and $b equivalent? |
$a === $b |
are $a and $b identical? |
$a > $b |
is $a larger than $b? |
$a >= $b |
is $a larger than or equal to $b? |
$a < $b |
is $a smaller than $b? |
$a <= $b |
is $a smaller than or equal to $b? |
as you already know, you can use ! to reverse any comparison but there is shorthand for some of these.
| php | action |
|---|---|
$a != $b |
shorthand for !($a == $b) |
$a !== $b |
shorthand for !($a === $b) |
you have already seen && in action but it can be used when comparing values, too. it also has two partners.
| php | action |
|---|---|
($a && $b) |
true if $a and $b are both true |
($a || $b) |
true if at least one of $a and $b is true |
($a xor $b) |
true if $a or $b is true but false if both are true |
it is also possible to use and for && and or for || but i recommend avoiding it for some technical and performance reasons.
you have already seen ? and : used to check if something is true and return one of two possible results. this also has a partner.
$a = $b ?? $c;
if $b has a value, $a will be set to $b. if not, $a will be set to $c.
on most systems, php defaults to using timezone 0 (utc) so you'll need to set your timezone if you don't want to use utc for this assignment.
date_default_timezone_set("America/Vancouver");
you can find a list of the possible values on wikipedia at https://en.wikipedia.org/wiki/List_of_tz_database_time_zones if you don't know the tz code for yours. they're usually named after the main cities in each zone. here are canada's for quick reference...
America/Vancouver
America/Edmonton
America/Winnipeg
America/Toronto
America/Halifax
America/St_Johns
north, central and south america are all prefixed with America for reasons nobody remembers, these codes having been set decades ago before php was created. they're not specific to php.
you can pass values to the date command to return specific versions of the date and time. they always return strings so, if you need to perform complex calculations with them, you may have to be specific about treating them as integers if that's important.
the unconverted value of the current date and time is in unix time, something we'll talk about later. it's not relevant to most of what you'll want to use in practice with the date command.
date("o.m.d H.i.s") // 2176.08.17 22.04.16
there's a long list of possible codes but here are some of the common/useful ones...
| code | result |
|---|---|
| d / j | day of the month with/without leading 0 |
| l / N | day of the week as text/number |
| z | day of the year |
| W | week of the year |
| m / n | month of the year with/without leading 0 |
| F | month of the year as text |
| L | is it a leap year? (1/0) |
| o | year |
| H / G | hour with/without leading 0 |
| i / s | minutes/seconds with leading 0 |
| u | microseconds |
| e | timezone |
| I | is it daylight savings? (1/0) |
| Z | timezone offset in seconds |
| U | unix time |
date takes an optional second parameter to use a date/time other than the current moment as a unix time integer. this is particularly useful in cases where you want to store the date/time and use it for comparison later.