Now I'm sure you've heard that programming is all math. Right? Well it's time for math. Let's get started.
Imagine a crazy maths problem here. My blog doesn't process LaTeX math rendering stuffs.
Now solve for X.
Just kidding. Actually, there's no X in that equation. In fact, it's not even an equation, so that was a terrible joke. Hey! They can't all be side-splitters. The truth is, I have no idea what that mess does either. We aren't all math gurus.
Let's try something that's a little bit closer to my own level of mathematics. You know how to make a PHP file, and you know how to open and close PHP tags. So let's jump straight into a PHP file. We'll call it
math.php. Here's the content.
<?php 3 + 3; ?>
Actually, hold on a second. We aren't going to output anything after our PHP code. Why bother with the closing tag? The truth is, most PHP developers omit this tag if there's no content that will follow our PHP code. Let's do that.
<?php 3 + 3;
Right, just in case your math skills aren't quite as sharp as my own, let me help you out a little. When you add three to three you get six. Okay, now you're ready.
3 + 3; contains a statement. It's a line of PHP code that will be evaluated by PHP. They normally end with a semi-colon. It looks like this:
;. You're gonna forget about them all the time at first, but don't worry, soon you'll even be ending your sentences with them;
Given that you now understand basic addition, what do you think will be the output when we execute this file?
Seven point five.
Well, special reader, let's see if you're right. Go ahead and run
php math.php to see what happens.
Woah! Absolutely nothing. This language is stupid. Let's give up. Okay, I'm kidding again. I have a cheesy sense of humour, don't worry, you'll get used to it.
Why didn't we get any output? Well, it's because we didn't tell PHP to output anything. PHP is obedient. Let's go ahead and tell it to give us the answer. We'll use
echo. It's a PHP language construct that will allow us to see the result of a statement.
Let's alter our statement to include
<?php echo 3 + 3;
There we go. We place
echo before the statement that we want to see the result of. Let's try running our application again! Here we go...
Woohoo! Six! NOT SEVEN POINT FIVE! Now that's what I'm talking about. We get to see the result of our first statement evaluation with PHP. That's exciting stuff, right?
I could have done that on a calculator.
I know, I know. It's not exactly rocket science. Rocket science will be covered in a later chapt... Wait, I've already told that joke in another book. I need to get some new material.
I know that our
3 + 3 example is simple code, but we'll soon get to bigger and better things. Did you know that there are more mathematical operators? I'm sure some of these ring a bell.
+ Addition - Subtraction * Multiplication / Division % Modulus
Now, I'm sure you'll have seen seen some of these operators before. I know that multiplication and division look a little different to the signs that you may have learned about in school. This is common to most programming languages, and you'll find that the division sign is definitely easier to type on a keyboard. Don't let them worry you, before too long you'll be completely used to them.
If you've not used the 'Modulus' operator before, then it's simple to explain. It can be used to calculate the remainder of a division. For example, the operation '3 % 2' would result in the figure '1'. It's commonly used to determine whether a number is odd or even by dividing by two.
Now let's give PHP something hard to think about, shall we?
<?php echo 4 + 3 * 2 / 1;
So, what's the result? Well it can be difficult to calculate in our heads because we don't know which order to process the pairs of calculations. Should we add 3 to 2 first? Or maybe divide 2 by 1 first. Hmmm. Tricky!
Of course, in mathematics we learn to use rounded brackets to separate the concerns of an equation. We can do the same with PHP. Let's give it a go.
<?php echo (4 + 3) * (2 / 1);
Now we can be sure that
4 + 3 and
2 / 1 are evaluated first, and the resulting values are multiplied. Great, we run our script and get the result...
Awesome, but isn't that cheating? What would we get without the brackets? Let's take them out again.
<?php echo 4 + 3 * 2 / 1;
So what's the result? Let's run our script.
That's a totally different figure. Why is that? Well, it's because PHP isn't handling our operators in the same order. Let's take a little time to learn about the order of our operators.
Here's how PHP handles the order of operators.
* Multiplication / Division % Modulus + Addition - Subtraction
The operator with the highest priority can be found at the top of the table. So this means when PHP examines
4 + 3 * 2 / 1 it will first calculate
3 * 2 = 6, then
6 / 1 = 6 and finally
4 + 6 to give us the answer
When I'm writing mathematical lines of code, I like to use brackets to avoid any confusion. I also find that it helps to clarify the intent of the line, causing it to be more readable.
PHP code is parsed procedurally. This means that it is read and executed on a statement by statement basis. While it's possible to put more than one statement on a line, this is uncommon amongst PHP developers. This means that we can also approach the code line by line. We can see this in action by adding more statements to our PHP file. Let's try the following.
<?php echo 2 + 2; echo 3 + 3; echo 4 + 4; echo 5 + 5;
Now, let's execute the file...
FORTY SIX THOUSAND GIGAWATTS!?
Calm down reader! We only told PHP to output the results, not to place spaces or newlines into the output. This means that PHP has calculated the values correctly. If we space out the result that PHP has given us like so...
4 6 8 10
...then we see that the calculations are in fact correct. It's just that PHP is very obedient and has outputted the values directly after one another.
I've mentioned many times before that PHP is a flexible and lenient language. Let's put that to the test, shall we? Up until now, our statements have a single space between each 'word' (or number). Let's add some extra spaces in an inconsistent format to see what happens. Here's our modified code.
<?php echo 2 + 2; echo 3 +3; echo 4+4; echo 5+ 5 ;
While it doesn't look very pretty, if you were to execute the code you'd find that it will work perfectly. PHP doesn't care about the amount of white space between the words within its code. It just deals with it. (Insert dog with shades...)
You'll notice that some of the arithmetic operations, for example
4+4, don't require a space at all. While this is true, it isn't consistent for all syntax variations. For example, consider the following snippet.
<?php echo5 + 5;
If you attempt to execute this script, you'll find that PHP will throw a notice 'Use of undefined constant echo5 - assumed 'echo5'. This is because it doesn't know what the word
echo5 is telling it to do. For this reason, it's always best to place at least one space between your words.
As for statements, if we were masochistic we could choose to put all of the statements on a single line. Here's an example.
<?php echo 2 + 2; echo 3 + 3; echo 4 + 4; echo 5 + 5;
This is perfectly valid PHP, but you won't find many developers doing it. Having a single statement on each line makes it much easier to read and understand a source file. It also causes problems for version control systems!
We've seen that PHP doesn't care if you use multiple spaces in its source code, but it also considers a newline a whitespace character. This means that the following snippet is completely legal.
<?php echo 2 + 2 ;
Don't believe me? Go ahead and try it! While the code functions as intended, it's not exactly the most readable piece of code. If I catch you writing code like this then you're due for a spanking!
There is one practical use to breaking a line, however. If the line is exceedingly long then it also becomes a readability issue. We can resolve this issue by applying a new line at an appropriate reading length. Many developers also apply four spaces (or your current tab setting) to the next line to indicate that it is a continuation. This is similar to how formal works of text use an indented sentence to indicate a new paragraph.
Here's an example of a line break for readability purposes.
<?php echo (3 * 5) / (7 / 12) * (7 * 6) + (7 % 3) + (6 + 7) * (12 / 3);
That's some serious math, but hopefully you will find it much easier to read.
It's also worth noting that you can also place empty lines within your code to add clarity. Here's an example.
<?php echo 3 + 2; echo 7 * 7; echo 5;
So you see, PHP can be extremely flexible, but don't forget to add that end of line semi colon because it will never forgive you.
My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.
It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!