Operators

Somebody bring in the math squad. Relax, how complicated can standard arithmetic operators be? In PHP there are 6 groups of operators: arithmetic, assignment, increment/decrement, comparison, logical, and array operators. We will just deal with the first 3 for now. Quick note: We are going to assume from now on that the code is inside the <?php ?> tags.

Arithmetic Operators

Example
    $a = 3;
    $b = 7;
    print $a + $b . "<br/>"; //Addition with the " . <br/>" being a line break
    echo $a - $b . "<br/>"; //Subtraction
    echo $a * $b . "<br/>"; //Multiplication
    echo $a / $b . "<br/>"; //Division
    echo $a % $b . "<br/>"; //Remainder aka Modulus
Result

10
-4
21
0.42857142857143
3

Nothing special here, they are pretty much standard across most languages.

Assignment Operators

You have already used one of these! See, you’re a genius and you didn’t even know it. The PHP assignment operators always have an = somewhere in the statement. The rest of the assignment operators are more like shortcuts. You can use them by throwing the assignment operators in front of the =. Let’s take a look.

Example
    $a = 3;
    $a += $a;
    echo $a;
    echo "<br/>";
    $b = 7;
    $b *= $b;
    echo $b;
Result

6
49

You’re smart, and you can figure out how to use the rest of them. As you can see with the variable $a, we basically add it to itself, which gives us 6. With $b, we multiple it by itself, which gives us 49. It’s literally just as simple as that. If you don’t want to use them, you don’t have too. Just have fun writing out the full $a = $a + $a; or $b = $b * $b;.

Increment and Decrement Operators

Four possible outcomes occur from increments and decrements. Notice the placement of the increment or decrement operator around the variable.

Example
    $a = 3;
    $b = 3;
    $c = 7;
    $d = 7;
    echo ++$a . "<br/>"; //adding 1 to $a before we echo (where the  . "<br/>" is a line break)
    echo $b++ . "<br/>"; //adding 1 to $b after we echo
    echo --$c . "<br/>"; //subtracting 1 from $c before we echo
    echo $d-- . "<br/>";//subtracting 1 from $d after we echo
Result

4
3
6
7

If you have ever messed with these guys before, you know what is going on here. If not, just understand that the position of the increment or decrement operator tells us when the action on the variable happens. In the first example, echo ++$a; increments the variable before we echo it out. However, in the second example, echo $b++;, we don’t increment the variable until after we echo it to the screen.

Date and Time

PHP Date and Times are just as frustrating as any other languages. The main issue of Date and Times is that they are entirely different strings that both have strong importance on position and number of characters. For example, a PHP date is usually in the format of “2013-02-01” and times always seem to vary. This is because, we as the great thinkers of the world, created a ridiculous time system with random values instead of some metric like construction. Of course, there is entirely a purpose for time’s current format, but we can both agree that it is not programmer friendly.

What we both know is that time and date is a rather useless distinction. In certain definitions of time, it also implies the date. So, from now on I want you to think of time also containing dates. It is much more useful to place these together and you probably will not give me a great reason to separate the two after this tutorial. First, let’s get into explaining timestamps and some PHP date and time functions.

PHP Timestamps

The PHP timestamp is a Unix timestamp that tracks the number of seconds since January 1, 1970 because we apparently believe milliseconds are useless. Nevertheless, let’s create a timestamp.

Example
echo time();
Result

1359780799

So, we just use PHP’s time function with default parameters to create a timestamp of this very moment (well, the moment I created this tutorial). Why would we want something like that when users cannot understand its format? First, it is a very consistent and easy to manipulate number. Second, I will show you how to format the timestamp into PHP dates and times in just a second. Also, note if you just want the current time, you should use time, but you should use mktime for custom datetimes.

PHP Dates

Using our newly created timestamp, we can format it into a date that the user can understand.

Example
echo date("Y-m-d","1359780799");
Result

2013-02-01

Boom! Now, we have a formatted date string that users can understand. Now I will go on a small tangent and emphasize my extreme approval of this particular format. Sure, “2013/02/01” is equally valid, but the hyphens seem to be more universal and easier to work with. I know I do not particularly provide a strong case for the date format, but if you have no preference, take mine!

PHP Times

Do you remember my tangent of times also include dates? Well, the guys that created PHP must have agreed with me. The PHP date function also can format timestamps into “Times”. Let’s see how to create a readable time.

Example
echo date( "H:i:s","1359780799");
Result

21:53:19

Well done. Now, we have the current military time that I created this tutorial. I know you might be thinking, “How do I create a timestamp that is not the present?”. Relax, we will get to it in just a moment.

PHP Date and Time

Now, let’s mix it up a little bit and create our own time and not the current time. We want to format this into a full date and time string.

Example
echo date("Y-m-d H:i:s",mktime(6,30,51,12,01,1999));
// mktime(hour,minute,second,month,day,year)
Result

1999-12-01 06:30:51

Now, that is a lot to digest. We have created a full date and time string using special formatting with the PHP date function. mktime actually has parameters this time, which is how we create a custom date and time that is not the present. In order, the mktime parameters are hour, minute, second, month, day, and year. See how much easier it is to work with timestamps instead of creating dates and times separately? The PHP date function has a lot of different formatting values. I have included the references below. Feel free to tinker around with this in the first parameter of the date function to see how the characters actually format the string.

PHP Date and Time Formats

a ‘am’ or ‘pm’ (lowercase) pm
A ‘AM’ or ‘PM’ (uppercase) PM
d Day of month, a number with leading zeroes 20
D Day of week (three letters) Thu
F Month name January
h Hour (12-hour format – leading zeroes) 12
H Hour (24-hour format – leading zeroes) 22
g Hour (12-hour format – no leading zeroes) 12
G Hour (24-hour format – no leading zeroes) 22
i Minutes ( 0 – 59 ) 23
j Day of the month (no leading zeroes 20
l (Lower ‘L’) Day of the week Thursday
L Leap year (‘1’ for yes, ‘0’ for no) 1
m Month of year (number – leading zeroes) 1
M Month of year (three letters) Jan
r The RFC 2822 formatted date Thu, 21 Dec 2000 16:01:07 +0200
n Month of year (number – no leading zeroes) 2
s Seconds of hour 20
U Time stamp 948372444
y Year (two digits) 06
Y Year (four digits) 2006
z Day of year (0 – 365) 206
Z Offset in seconds from GMT +5

String Variable

Onto the most flexible variable in PHP, the string variable. You might notice how I keep referring to strings as variables. However, strings are much more like objects with methods and properties. Only the string object’s properties is what you might think of as the string. However, I won’t discuss objects much in the early tutorials because they are a bit more complicated. You can manipulate a string in almost every way imaginable in PHP. Previously you already learned how to create a string variable by putting the actual string in quotes following the variable name.

Example
<?php
    $myVar = "Champions";
    echo $myVar;
?>
Result

Champions

Nothing special here. We are just echoing a string variable just like before. What if we want to join strings with other strings or strings with variables?

Joining Strings

The concatenation operator in PHP is a little bit odd in comparison. The . joins everything together. Weird choice isn’t it? I thought so.

Example
<?php
    $myVar = "Champions";
    echo "We are the " . $myVar . " of the world.";
?>
Result

We are the Champions of the world.

Yes, I was rocking out to that song while writing this. You should too! We have the string “We are the “ that we join to $myVar and again to ” of the world”. That is truly all we have for the simple side of strings. Check out the PHP Strings tutorial to get into more advanced string functions.

Variables

This is PHP, and we want to be dynamic. What’s more dynamic than a variable? Nothing. I know we are all still a little scared of variables from our crazy high school math teachers, but in reality, they are possibly your greatest asset in PHP. However, PHP variables have a few strict rules, which in my opinion is the best way to have them.

Variable Rules

  1. All variables must start with a $
  2. All variables must only contain alpha-numeric characters with the only exception of _ (an underscore)
  3. All variables must start with a lowercase letter or an underscore.
  4. All variables are case sensitive, meaning that x and X are different variables

Unlike other languages, the syntax of creating a variable is remarkably simple. You don’t have to put a type keyword in front of the variable name in order to declare it.

Example
<?php
    $myVar = "Greetings";
?>

You just created the variable $myVar with a value of the string “Greetings”. PHP is smart enough to recognize what type of variable you are trying to define, well, kind of. We will get into more complex variables later. Let me show you how smart PHP is with variables really quick.

Example
<?php
    $myVar = "1";
    $myVar2 = true;
    echo $myVar;
    echo $myVar2;
?>
Result

11

Don’t flip out. I know, I’ll explain it in a second. First, we print out $myVar that gives us the integer 1. Next, we print out $myVar2, which returns the boolean true (1 is equivalent to true in the boolean type). Also, notice that after the echo, we didn’t use quotations around our variable. With echo in PHP, you don’t use quotations around the variables. You only use quotations to tell PHP that something is a string.

Variable Scope

Don’t paint yourself in a corner. Understand scope before drafting your code full of variables.

Example
<?php
    $myVar = "Greetings";
    function sampleFunction()
    {
        $myVar = "No Greetings";
    }
    echo $myVar;
?>
Result

Greetings

I know you might not understand what a function is, but we will get to functions later. For now, just understand that the variables in a function are segregated from the rest of the code, unless you override it, which I will never show you how to do. It’s terrible practice. Back to the example, why didn’t it echo “No Greetings”? It is because the $myVar = “No Greetings”; is confined inside of the sampleFunction‘s scope. This may be a pain sometimes, but the scope is essential in writing solid code. We don’t want variables overriding everything we type. So, just be smart when creating your variables. Think about where they need to be and what they are trying to accomplish.

References

Switch Statement

The PHP switch statement is pretty much a simplified way to write multiple if statements for one variable. As you use them, you will begin to realize why they are much more convenient that writing a whole lot of if statements or elseif statements. If statements check one conditional, but switch statements can check for many different cases. The simple syntax of switch statements provide more readable code as opposed to using a lot of else if statements.

Example
$x = 3;
switch($x)
{
    case 1: //this statement is the same as if($x == 1)
        echo 'Case 1 was executed.';
    break;
    case 2: //this statement is the same as if($x == 2)
        echo 'Case 2 was executed.';
    break;
    case 3: //this statement is the same as if($x == 3)
        echo 'Case 3 was executed.';
    break;
    case 4: //this statement is the same as if($x == 4)
        echo 'Case 4 was executed.';
    break;
    default: //this statement is the same as if $x does not equal the other conditions
        echo 'Default was executed.';
    break;
}
Result

Case 3 was executed.

The syntax is slightly different than an if statement. The entire switch is implicitly using the == that we saw in the if statements earlier. However, we can see that we do not have to repeat that boring comparison operator over and over. Instead, the case is followed by the conditional variable. After the case 1, we see a :. After that colon, we have our statements to be executed. Finally, we come to the break, which signals the end of the if like statement. If we didn’t use break, PHP would continue to execute the other conditions in the switch statement. So, use break at the end of your case block to break out of the switch statement unless you want the following cases to be executed. As for the default:, it means that if none of the other conditions are satisfied, do the statements following the default:. The default term is comparable to the else statement.