codeswan blog

PHP: Wrapping Things Up

If you’ve been reading my posts about coding the last few weeks, then you’re pretty much ready to deal with any of the PHP that you come across in a WordPress theme. Heck, maybe you’re even ready to write your own PHP! I’m so proud… you’re all such good students.

But before we move on to the next part of your theme – the actual HTML in the body that displays what you see on your website – there are a few last things to wrap up regarding PHP.

Operators

There’s one last thing that we haven’t discussed much in PHP, that you’re guaranteed to see in almost any PHP code out there. Operators. It might seem like we’re taking a step back into middle school math, but this will be painless. I promise.

First, we have the arithmetic operators: +, -, /, *, %. These do exactly what you’d expect: add, subtract, divide, multiply, and take the modulus (the remainder of one number divided by another. 5 % 2 is 1). You can also negate a value by putting – in front of it. Easy.

Then, there are the assignment operators. = is obvious, you’re just setting one value equal to another, like this: $a = 5. Then there’s += which means that you add the value to the variable. So $a += 2 would be 7, because we already set $a to 5. That works for numbers, but what about strings? Here you use .= which tells you to concatenate one string onto the end of other. Pretty much just sticking them together. So if we started with $b = ‘Hello ‘; and then did $b .= ‘world!’; $b would end up as ‘Hello world!’. You do something similar if you want to stick a variable in the middle of a string. You could just do $c = $b . ” What’s up?”; and it would show up as “Hello world! What’s up?” (Notice that I used double quotes to surround the string there. Since we had an apostrophe in “what’s”, I didn’t want it to be read as a closing single quote, which would screw things up. Luckily, in PHP you can just use double quotes instead, and avoid that problem.)

Next are the comparison operators. We already know that = sets a variable equal to a value. But what if we want to test to see if two things are equal? We definitely don’t want to set the variable equal to the value we’re testing for. That would be bad. So instead we use == or ===. $a == $b will be true if $a is equal to $b. $a === $b is the same, but also adds the constraint that $a and $b have to be the same type. (But why? Well, what if you wanted to test to see if $a is equal to the boolean value true? If $a is any non-zero, non-null value, then when you translate it to boolean it shows up as true. But that’s not what we want. So instead we’d use === to say that it’s only true if $a is the boolean value true, and if it’s not boolean, then it’ll show up as false.) Then we have != which tests to see if two values are not equal, and !== to see if two values are either not equal or not of the same type. The opposite of == and ===, if you will. The other four comparison operators should be familiar from your old math classes: <, >, <=, >= simply test to see if one value is less than, greater than, less than or equal to, or greater than or equal to another.

Then there are the incrementing and decrementing operators. ++ increments (adds 1 to) a variable. – – decrements (subtracts 1 from) a variable. Put it beforehand if you want to increment/decrement before the value is returned (if you start with $a = 1, echo ++$a; will print out ‘2’). Put it afterward if you want to increment/decrement after the value is returned (if you start with $a = 1, echo $a++; will print out ‘1’, and then if you echo $a; after that, it will print out ‘2’).

Next we have logical operators. We’ve already talked about && and ||… ($a && $b) means that both $a and $b have to be true in order for the entire expression to be true, and ($a || $b) means that either $a or $b or both have to be true for the expression to be true. (You can also use ‘and’ instead of ‘&&’, and ‘or’ instead of ‘||’.) If you want either $a or $b to have to be true, but NOT both to have to be true, then you can use $a xor $b. Lastly we have !, which means not. (!$a) means that $a has to be false for the expression to be true. Make sense?

Teacher, Teacher, I Have A Question

Now that we’ve explained the basis of PHP for you, where can you go to find more information?

Well, you can always come back here, of course. For now I’m moving on to talk about HTML, CSS, and JavaScript, but you can be sure there will be more posts about PHP in the future as well.

PHP.net is an excellent resource. Any time you ever have to look up a function that you (or your web developer) didn’t create on your own, chances are you’ll find the documentation for it here. And it goes the other way around too – whenever you need to figure out how to do something (for example, what if you want to display today’s date? or change a string to all lowercase?) you can do a search for it, and 90% of the time you’ll find a pre-made function that does exactly what you need, on PHP.net. And while you’re there, check out the comments on every page – there you’ll find discussion and examples about how other programmers have used these functions.

w3schools.com is another great resource. While PHP.net is all about documentation, w3schools.com tends more towards tutorials and examples how to use things.

If you want to purchase a book about PHP, Head First PHP & MySQL is an excellent resource. I love the Head First series for learning any sort of programming language – they explain things in ways that are very easy to understand, and even have games at the end of every chapter to help you remember what you learned. I have a couple of the Head First books from back when I was first learning, and I can definitely vouch for how helpful and easy to use they are.

I Am Here For You!

If there’s anything else – anything at all – you want to know about PHP, or coding in general, just ask! Even if it’s something that can be found in any of those references, I’m always happy to help. Whether it’s something confusing from the code in your theme, or questions about different web technologies, or anything else coding- or tech-related, I’m here for you. Really. I want to help you guys. And maybe you’ll even get a blog post written specifically to answer your question!

in Coding, PHP, Tutorial | Leave a comment

PHP: Real Code, And A Game Of Hangman

I’m such a tease. For the last two weeks, I’ve been tempting you with a game of hangman, promising you real PHP code that actually works… none of that silly pseudo-code business. Can you blame me? I’ve got to keep you all coming back somehow…

Well. Today, I tease no more, my friends. Not only do I have real code for you in today’s blog post, I actually have code that you can download. For free. With tons of comments throughout that explain everything. Yes, I’m awesome like that.

And, even better, you can actually run this code on your own server (or hop on over to mine), and play an real working game (or several) of hangman. (No, really! Click the link, it’s awesome. And then come back and read the rest of the post.)

THE CODE: the abridged version

If you download the code itself, you’ll see there are a few things I don’t talk about today, like sessions and form HTML. These are way, way beyond the scope of today’s post, although I may get to them someday. But I’ve tried to leave comments within the code that will explain everything so it’s not too difficult to understand.

For the purpose of today’s post, this is the code we’re looking at, which is really just an excerpt of the code you can download:

$word = 'sushi';
if ($guessLength < strlen($word) && $hangman < 6) { $message = "The game's not over yet..."; $match = false; $guess = [users guess]; $positions = array(); if (in_array($guess, $alreadyGuessed)) { $message = "You already guessed '" . $guess . "'!"; $isGuessed = true; } if (!$isGuessed && $guess != null) { $alreadyGuessed[] = $guess; for ($j = 0; $j < strlen($word); $j++) { if (strcmp(substr($word, $j, 1), $guess) == 0) { $match = true; $positions[] = $j; } } if ($match == true) { foreach ($positions as $k => $position) {
if (strcmp($display[$position], '_') == 0) {
$display[$position] = $guess;
$guessLength++;
}
}
} else {
$hangman++;
}
}
}
echo $hangman . ' bad guesses.';
foreach ($display as $l => $letter) {
echo $letter . ' ';
}
echo $message;
Like always, let’s go through it, line by line.

Initial Variables

$word = ‘sushi’; This one’s easy. (Although in the actual game code, it randomly chooses from a list of words instead.) All you’re doing is setting your $word variable equal to the value, ‘sushi’. Sushi has to go in quotes (technically you can use either single quotes: ‘ ‘ or double quotes: ” “) because it’s a string – a bunch of characters all put together.

In the actual code, there are a few other variables like $hangman, $guessLength, $alreadyGuessed, $hangmanImage, and $display that are also set, using sessions. For the purpose of today, you don’t have to know how it’s done, just know that they’re there.

The Outer If-Statement

Next, we open the if-statement. (Yes, it was a while loop in last week’s pseudo-code. While hypothetically that works great, since in a true human game it’s continuous, it doesn’t work quite so nicely in the computer world. So we use an if-statement instead.) Since it’s an if-statement, we need a condition to test, right? Here, our condition is actually two conditions, that both must be true. The first one, $guessLength < strlen($word), says that we're only going to keep playing the game so long as the number of letters that we've guessed right is less than the number of letters in the word. Because if you think about it, there's no point in continuing to play the game if you've already guessed the entire word, right?

The second condition in the if-statement, $hangman < 6, tells us that we're only going to keep going if there are less than 6 parts in the hangman. (Head, body, two arms, two legs.) If the hangman is complete, meaning there are already 6 parts there, then the player has lost the game and we don't want to continue playing.

You see the opening curly brace right after the conditions, but where’s the closing one? Remember – just like in HTML, your PHP code is like an onion. So each layer has to completely enclose the layers within it, and be completely enclosed by the layers outside of it. So the closing curly brace for our if-statement is at the end – after all the other inner loops have closed. The indentation makes this simple – you can easily see the closing brace because it’s on the same indentation level as the opening one.

Even More If-Statements

Just inside of the outer if-statement, you see a few more statements before your for-loop. The first is a variable that’s set to text which we’ll print out later. Then two variables: $match which is set to the boolean value false, and $guess which is set to the single letter that the user has guessed. Super easy. Making sense so far?

Before you step inside the for-loop, you also create an array called $positions… but don’t put anything in it quite yet. But we will, soon. Don’t worry.

Then a couple of if-statements. By now, you should be able to make some sense of them. The first one is simply making sure that the letter isn’t one you’ve already guessed, and printing out a message if you have. And the second one is saying that if you haven’t guessed the letter and your guess isn’t blank, then keep going with the code inside. You put the guess into the array of letters you’ve already guessed, so you can’t choose it again… and then you get to your first for-loop.

Moving On, The For Loop

Next comes your for-loop. Remember last week, when I explained the code you see here? Well, this week you see it in action. We’re starting at zero ($j = 0;), looping for the length of the word ($j < strlen($word);) and incrementing by one each time you go through the loop.

Then there’s an if-statement. It’s the fourth one you’ve seen in today’s code, so you’re sure to be cool with it by now. And I know you’ve seen that strcmp() function before. So what’s that substr() function do? It takes the sub-string of the string $word, starting at position $j in the string and taking the next 1 letter. So since our word is ‘sushi’, and if we’ve looped so $j = 1, substr($word, $j, 1) will be ‘u’. (“But why? Isn’t the first letter in ‘sushi’ ‘s’?” Yes, however remember that in programming, you always start at zero. So the letter at position 0 in ‘sushi’ is actually ‘s’, and the letter at position 1 is therefore ‘u’.)

So, if the substring is the same letter as the one the player guessed, then we’ll say that yes, there is a match – we’ll set $match = true;. In addition, we set $positions[] = $j;. But wait, what does that mean? Like the name suggests, the $positions array is an array that tells us which positions in the word have been guessed correctly. So if our word was ‘sushi’, and the player guessed ‘u’, then we would add $j (which at that point equals 1) to the array.

And we keep looping through the for-loop until we’ve checked your guess against every letter in the word.

Even Better, A For-Each Loop

Another if-statement. Yes, I know, y’all are experts at if-statements by now. I’m so proud of you. So we’ll skip over that, and look at that foreach loop. All it’s saying is that for each object in the $positions array, we’re going to call the key $k, and the value $position. (Remember that they’re paired up – every key matches up with a value. Like how every SSN matches up with a person.) So that little block of code just says, if the position you’re looking at still shows up as _, meaning you haven’t guessed it yet, then put in the guessed letter. Otherwise, if there isn’t a match, then add a part to the hangman.

Hold On… That’s It?

Yep. That’s all. As you can see, all that’s left after that are echo statements (and another sneaky but simple foreach). See? Coding isn’t so hard now, is it?

in Coding, PHP, Tutorial | Leave a comment

PHP: For, While, and other Loopy Things

If you think back to last week’s introductory post about loops in PHP, you’ll remember I gave you some pseudo-code that described a program to run a game of hangman. And then I left you hanging.

(Yes, that pun was totally intended.)

And then we played a game of hangman in the comments. It was awesome.

But you’ll recall that I did promise to go into detail about exactly what the while, for, and for each loops are, and how they work. That’s exactly what I intend to do today. So, first things first. Take a look once more at the pseudo-code that I introduced you to last week:choose the word to be guessed;
set the hangman to empty;
while (the word is incomplete and the hangman is incomplete) {
tell the person the game is still going;
$match = false;
$guess = the persons guess;
for (each letter in the word) {
if (letter is the same as $guess) {
$match = true;
remember which position this letter goes in;
}
}
if ($match == true) {
display positions where the letter is the same as the $guess;
} else {
add a part to the hangman;
}
}
For the most part, that seems to all make sense, right? Everything is in plain English, and it tells you exactly what the code in the program is doing. But then you see the while loop, and the for loop… what does it all mean? Let’s go from the outside-in.

While

While a condition is still true, then continue looping. This is probably the easiest of the three, because you’ve seen something of a similar layout before. Remember from my article about if-statements a couple of weeks ago, that the stuff between those parentheses after ‘while’ and before ‘{‘ are the conditions. They’re the things that you test for truthiness, and if they are true, then you do the stuff that’s between the curly braces.

So here we’re saying, while (the word is incomplete and the hangman is incomplete) {
do stuff
}
If the word is incomplete, and the hangman is incomplete, that means that the player has neither won nor lost the game yet, right? They still have chances to guess more letters. So that’s pretty much saying that while the game is still going, then keep doing all that stuff between the curly braces. The reason we use a while statement for this is because we don’t know how long the game will be going. If it’s a short word, you could win or lose in three tries, or it could also get up to 26 guesses.

Side note: the while loop tests the condition before it runs the code between the braces. But what if you wanted the condition to be tested after each time you run the code? Then you would use a do-while loop. Like this:do {
the stuff you want to do
} while (your condition);
Pretty much the same as a normal while-loop, just… backwards.

For

For every integer starting at one number and ending at another, incrementing by a certain amount each time, loop once.

It sounds a lot more complicated than it actually is. I promise.

For-loops generally look like this:for ($i=0; $i<10; $i++) { do stuff } Let's break it down. $i=0 tells you that you have a variable $i that starts at zero. $i<10 means you want it to continue looping so long as it is less than ten. And that last bit, $i++, tells you that $i should increment by one at the end of every loop. So it will run through the code inside of the loop when $i is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9... and then it will stop when $i == 10 because it is no longer less than ten. Your variable doesn't have to be called $i (though it quite often is). It can start at any integer and end at any integer. And while you'll usually see the simple increment-by-one expression that we used here at the end, you can have any sort of expression at all that you want to use.

But wait... that doesn't look like the for-loop that's in the pseudo-code.

You're right. So instead, look at what it would look like in real code: for ($i=0; $i See? Now it looks exactly as a for-loop should. (That strlen() function simply gets the length of the string... or in our case, the length of the word that the player is supposed to be guessing, so we can loop through every letter to see if it's a match.)

For Each

For each thing in some sort of group of things, loop once. This group of things is known as an array.

"But wait," you wonder, "what's an array, and why on earth would I use one?"

An array is nothing more than a grouping of things. Yes, I know, I just said that. But it's no more complicated than that.

Imagine you have a handful of coins. (An array of coins.) And you want to put them in a piggy bank, but it's got a tiny slot so you can only put one in at a time. So you might do it like this:foreach ($handfulOfCoins as $coin) {
put coin in piggy bank
}
$handfulOfCoins... that's your array. And you're saying that each thing in this array is a $coin, and you want to do the code inside the brackets to every single $coin in your $handfulOfCoins.

Now That Wasn't So Hard, Was It?

You're catching on. I just know you are. In fact, I have so much faith in you... next week, I'm going to show you what the real code for this hangman program looks like! And, even better, we're going to code our very first real PHP program!!

Aren't you excited? I know I am.

It's going to be awesome.

in Coding, PHP, Tutorial | Leave a comment

PHP: Getting Loopy

Have you ever played hangman? I used to, all the time. Especially when I was bored, and didn’t have a book to read or anything else to do. This was before the 24/7 connection of computers and iPhones, of course.

If you haven’t, let me explain: hangman is a simple little word game. One person thinks up a word, then writes out dashes and spaces to represent the number of letters in the word. If my word was ‘sushi’, I’d write: _ _ _ _ _. The other person’s job is to guess the word, letter by letter. For every letter they guess that isn’t part of the word, a part of the hangman is drawn – until either the hangman is completed and they lose, or they guess the entire word and win.

But what does this have to do with PHP code… ?

So You Want To Write A Program…

Say you wanted to write a PHP program, so you could play hangman on your computer. How would you do it?

If you’ve been reading my coding series, your first thought might be, “If statements!” Okay, so let’s see how your pseudo-code might look if you used a bunch of if-statements to write the program: if (hangman is not finished) {
if (word is not finished) {
if(the first letter in the word matches the guess) {
display the letter
indicate that there is a match
}
if (the second letter in the word matches the guess) {
display the letter
indicate that there is a match
}
if (the third letter in the word matches the guess) {
display the letter
indicate that there is a match
}
if (the fourth letter in the word matches the guess) {
display the letter
indicate that there is a match
}
if (the fifth letter in the word matches the guess) {
display the letter
indicate that there is a match
}
if (there is not a match) {
add a part to the hangman
}
}
}
And that’s only for one guess, for a word that’s only five letters long. What if you had a 20-letter phrase? Or 15 guesses?

Yuck. As you can see, it gets real ugly, real quick.

So What’s A Programmer To Do?

Lucky for us, there are more tools in our coding toolbox than just the if/else statement. (Can you imagine if you had to build a house with just a hammer? Darn near impossible.) So how would I code something like this?choose the word to be guessed;
set the hangman to empty;
while (the word is incomplete and the hangman is incomplete) {
tell the person the game is still going;
match = false;
guess = the persons guess;
for (each letter in the word) {
if (letter is the same as $guess) {
match = true;
remember which position this letter goes in;
}
}
if (match == true) {
display positions where the letter is the same as the guess;
} else {
add a part to the hangman;
}
}
You see, we also have things like while statements, for statements, and if I wrote it out as real code you’d even see a couple of foreach statements in there.

Okay. Time to explain.

Loops

Remember our if-statement last week? Each line in the entire statement would be read by your browser (or parser) once, and then when the parser was done with the statement, it would move on to whatever code came next.

That’s not how loops work.

Loops are, as the name suggests, sections of your code that the parser loops through several times. There are several different types of loops – some of which are the while, for, and foreach loops. (There’s also a do-while loop, but you’re a lot less likely to see it in most code. It’s almost exactly like the while loop, except… backwards. In the do-while loop the condition test is done at the end of the code block, instead of at the beginning like in a while loop.)

Those are what make it so you can write cleaner code, like my pseudo-code, instead of those messy repetitive if-statements.

You Can’t Just Leave Us Hanging Like This…

Yes, I can. Technically, I’ve given you all the resources you need to figure out on your own what all these loops do. Go ahead, click the links. You’re smart enough to figure it out, I know you are.

But if you prefer my explanation style to that of the authors at PHP.net? (You’re a sweetheart, really you are.) Then come back the next couple of weeks, when I go into detail about the different types of loops, and show you some real code that would actually create the hangman game for you.

And if you’re not sure if you prefer my writing style to theirs? Well… I’ve never claimed to be above bribing with homemade cookies…

in Coding, PHP, Tutorial | 2 Comments

PHP: On One Condition…

For the last couple of weeks, we’ve talked about functions and variables in your PHP code. But that’s not nearly all that there is to PHP. After all, there’s more to functions than just passing variables around (we have to do something to these variables, else what’s the point?) and functions aren’t the only way you can insert PHP functionality into your website.

It Must Meet These Conditions…

“If the user is logged in, they’re allowed to edit their profile. But if they’re not logged in, we’d better not let them even think about editing profiles.”

That sound familiar? It should. There are all sorts of websites out there that do something like this: Facebook, Twitter, Gmail… even your own WordPress sites. After all, you don’t want some stranger to be able to come in and make changes to your website without being logged in, right?

So how would you tell your code to do this? Just use a simple if/else statement. To put it in plain English, it’s something like this: if (user logged in) {
let them make changes
} else {
tell them "Sorry, you have to be logged in to do that."
}
(FYI, this format is something known as “pseudo-code”. Some programmers will write their code in plain English like this first, so they know exactly what needs to be done before they start coding. Then they translate it into actual code.) Although real user management systems are a bit more complicated, it really all boils down to a basic if/else statement.

Let’s break it down. First, you have the word “if”, and a condition between the parentheses. If this condition is true (if the user is logged in), then this will tell your browser that it should execute the code between that first pair of brackets (let them make changes). If it isn’t true, then it won’t execute that code and it’ll move on to the “else” statement, and execute the code between those brackets (tell them “Sorry, you have to be logged in to do that.”). Make sense?

But what happens if you need more than a simple true/false condition? What if, say, you want to display something different depending on what day of the week it is? Well then, you’d do something like this: if (Monday) {
print "Drag yourself out of bed, it's Monday."
} else if (Tuesday) {
print "The week's still getting started, it's Tuesday..."
} else if (Wednesday) {
print "Today's hump day..."
} else if (Thursday) {
print "It's Thursday! The Big Bang Theory is on today!"
} else if (Friday) {
print "TGIF!"
} else if (Saturday or Sunday) {
print "It's the weekend!"
} else {
print "Something went wrong... I'm pretty sure that's not a day of the week."
}
You see that the code will move through each “if” and “else if” statement until it finds one that’s true. Today is Thursday, so it will skip over the first three statements because they will all be false, and only execute the Thursday code and print “It’s Thursday! Allison’s day to post!” If all the “if” statements are false, then it will end up at that last “else” statement.

Taking Off the Training Wheels

As you can see, I wrote that entire if/else statement in pseudo-code. What would it look like if I wrote it in real code? if (strcmp(date("l"), "Monday") == 0) {
echo "Drag yourself out of bed, it's Monday.";
} else if (strcmp(date("l"), "Tuesday") == 0) {
echo "The week's still getting started, it's Tuesday...";
} else if (strcmp(date("l"), "Wednesday") == 0) {
echo "Today's hump day...";
} else if (strcmp(date("l"), "Thursday") == 0) {
echo "It's Thursday! The Big Bang Theory is on today!";
} else if (strcmp(date("l"), "Friday") == 0) {
echo "TGIF!";
} else if (strcmp(date("l"), "Saturday") == 0 || strcmp(date("l"), "Sunday") == 0) {
echo "It's the weekend!";
} else {
echo "Something went wrong... I'm pretty sure that's not a day of the week.";
}

It’s not as complicated as it looks. Those “if” and “else” parts are exactly like they were in our pseudo-code, so that’s nothing difficult. And we talked about how to use “echo” in your code last week, remember? (Don’t forget the semi-colons after each line of your code within the “if” statements!) The only thing that’s really new is that scary-looking stuff between the parentheses. Your conditions.

If you look closely, you’ll see that it’s just a couple of functions. You can tell because they’re of the form name(parameters).

“But there’s no semi-colon!” That’s okay. When you’re putting stuff between parentheses, like parameters in your functions or conditions in your “if” statements, you almost never use semi-colons. Except with “for” statements, but we’ll get to that later.

The first function I used was date($format). I knew I needed a function that would tell me what day of the week it is. The date function does exactly that. The parameter you pass in tells the function what information it should return about today’s date. I passed in “l” (lowercase L), which tells it that I want to know what day of the week it is. If instead I wanted it to tell me that today is Thursday, February 18, 2010 then I would pass in “l, F j, Y”. How do I know what letter(s) to use? I look at the PHP documentation for the date function, which explains all the parameters that I can pass into it.

Then I used strcmp($string1, $string2). “strcmp” stands for “string compare” – all it does is compare two strings to see if they are the same. In my if/else statement, I need to know which day of the week the date function returned so I know which condition will be true.

To figure that out, I use the strcmp function to compare the value that the date function returned to each day. If the values of the two strings are the same, strcmp will return 0. So for the first condition, we compare the day to “Monday”. Since today isn’t Monday, it won’t return 0. And since it doesn’t return 0, then strcmp() == 0 won’t be true, so it will move on to the next function. But when it gets to “Thursday”, strcmp will return 0 because today is Thursday. And since 0 == 0, the condition is true! So it will print out “It’s Thursday! The Big Bang Theory is on today!” (What? Yes, I’m a nerd. But you knew that already.)

Why do we use two equal signs? If you want to set a variable equal to something, you use one equal sign. If you want to see if a variable is equal to something, you use two. So for these conditional statements, where we want to see if our strcmp function is equal to zero, we use two equal signs (I’ll explain this more in a few weeks when we talk about PHP operators).

If you’re looking at the code, there might be one more thing that looks unfamiliar. What is that || thing? In our code, we want to print out “It’s the weekend!” if it’s the weekend of course, which means Saturday OR Sunday. So we need a way to say that the condition is true if today is Saturday OR if today is Sunday. That’s what the || operator does: it says, our condition will be true if “strcmp(date(“l”), “Saturday”) == 0″ or if “strcmp(date(“l”), “Sunday”) == 0″. Easy! (There are other operators, like AND or NOT, that we’ll discuss in future posts.)

Going in Circles…

Next week, we’re getting a little loopy. ‘While’ loops, ‘for’ loops, ‘foreach’ loops… we’re going to be going around and around in circles.

But don’t worry. I’ll try not to make you too dizzy.

in Coding, PHP, Tutorial | Leave a comment

PHP: Variables

Giving someone a present
Photo courtesy of Phu Son Nguyen

Last week we talked about what functions are in PHP, and I promised that this week I would explain more about what goes into a function and why on earth there are so many dollar signs in PHP code. So to put things into context before we jump right in, remember that we were discussing functions, kind of like this: function multiplyBySeven($int) {
$seven = 7;
$int = $int * $seven;
return $int;
}
‘multiplyBySeven’ is the name of our function (which, as you might guess, multiplies a number by 7), and we pass a parameter $int into it.

These Things Called Variables

“Alrighty then, Allison, tell us… what are all those dollar signs about? I thought we were talking about coding, not economics.”

Those dollar signs mean we’re talking about variables. Variables are basically containers that hold values that can change or vary throughout your code (hence the name).

It’s kind of like a present. Say you put something in a box and give it to a friend. Maybe that friend doesn’t change anything, and (*gasp*) re-gifts the present to someone else exactly as they got it. (You can pass the variable around into other functions or use it to change another variable without changing itself in any way.) Or maybe they just reuse the container, and put in another gift (a different value) before passing it along to someone else. (You can alter the variable’s value or even replace it with another value before you pass it elsewhere.) Make sense?

Another good way to explain how variables work is to show an example: Just as in our parameters example last week, you see that the variable $num starts out with a value of 10. But by the time it is returned, it has a value of 50. The ability to alter or change the value of variables any time you need to makes them very valuable in programming languages.

The naming conventions are essentially the same as for functions, except that variable names must always start with a dollar sign.

“But… $int has a dollar sign. I thought it was a parameter, because it’s between those parentheses after the function name?”

It is. It’s also a variable. You see, when you pass a value into a function, you want to be able to use that value within the function. Otherwise, what’s the point of passing it in? And in order to move a value around within a function, you need to assign it to a variable first. Therefore, anytime you pass a parameter into a function, it will always be assigned to a variable. But not all variables are parameters (like $seven in that first example). Get it?

Although in all our examples so far we’ve assigned integers to our variables, there are lots of other value types that can be assigned to variables as well. For example, you can have boolean variables ($boolTrue = TRUE; $boolFalse = FALSE;), string variables ($stringVar = “sushi”;), float variables ($float = 14.75;) (recall that integers are whole numbers, like 1 or -7. Floats, also known as floating-point or ‘double’ numbers, are non-integers that have decimal points), or even arrays and objects (which are way outside the scope of almost any WordPress theme, so I won’t go into them here.) You can even have a variable point to nothing at all ($nullVar = NULL;).

But what if you don’t want your variable to ever change? You use a constant. These are relatively rare in WordPress themes–you’re far more likely to see a variable than a constant. But just so you know, constants are always in all caps, and instead of defining them like you do variables ($num = 7;), you have to use the define() function to instantiate them.

That’s more than you need to know for WordPress themes, but if anyone’s curious, let me know in the comments and I’ll gladly explain further.

Little White Lie

Last week, remember how I told you that your PHP code always, always has to be surrounded by the <?php and ?> tags? Well, that isn’t entirely true. I mean, it is, I wasn’t lying to you, but… well… *sigh*

Technically, there are a few other PHP tag styles that you could use, such as <% %>, or <? ?>. However, it’s not recommended. These styles are much more rare than the <?php ?> tags, and not nearly as widely supported. So really no reason to talk about it, right?

The reason I bring it up is that I have seen some themes use PHP tags that are generally not recommended, and I figure you should know what’s going on even if it’s not the best way of doing things. They look something like this: What that does is put the value that you get from that function directly into your code. (It essentially says, “What goes right here is equal to this function.”) I believe it’s supported by almost all browsers, but technically it’s not recommended. Instead, you’re supposed to do something more like this, which does exactly the same thing: (That ‘echo’ before the function merely means that it’s supposed to “echo” the value from the function… or print it out into your code, so it’s visible in the final webpage.)

Moving On…

Thank goodness we got that all straightened out. We know what variables are now, but does this mean we’re finished with our PHP lesson?

Nope. Not even close.

Next,we discuss conditionals. Conditional statements, that is. Not the “If I told you, I’d have to kill you” types, but more like “If a user is logged in, then they get to see this page,” or “If you don’t read next week’s post, then you will be destroyed by the secret internet monster.”

If you think I’m joking, then you better come back next week to find out, huh?

in Coding, PHP, Tutorial | Leave a comment

PHP: Getting Functional

Dissecting the elePHPant
Photo courtesy of Phu Son Nguyen

Last week I introduced you to the elePHPant, and showed you how to differentiate the PHP in your code from everything else. But that doesn’t actually tell you what’s happening between the PHP tags… which is kind of the entire point of learning about PHP, right? So today we begin to dissect the elePHPant, and learn about everything that goes on inside.

Functions

So how do you make your PHP “do stuff” to your webpage? Well, there are several ways, all of which you are likely to see in your WordPress theme (or in any PHP code), and all of which we will discuss in the next couple of weeks. It essentially comes down to two methods: you can put your logic (yes, you have to use logic; no, it’s not as difficult as it sounds) inline in the code for your webpage, or you can put it elsewhere and import it into your webpage using a PHP function.

It’s similar to what we said about using class attributes to apply the same style multiple places in your code, or using a separate file for your header so that you can import exactly the same header into every page without having to repeat the code. If you’re only going to use a certain block of PHP code once in your entire website, then it makes perfect sense to put it inline. However if you plan to use the same code many times in your website, it’s far better to put it in a separate function (usually in a separate file such as functions.php), and then just call that code using the name of the function.

Okay, so how do you know if something is a function, and not… something else? That’s easy. Your basic PHP function looks like this: This breaks down into three sections:

  • Function Name: We called this function, “myFunction”. Notice that there are no spaces in the function name – instead we use something called camelCase, where the first letter in every word is capitalized. You are generally recommended to use only upper- and lower-case letters in your function names. Numbers are allowed but discouraged, and function naming conventions say you should only use underscores under very specific circumstances.
    (However, many people use underscores where you might find spaces, instead of camelCase, like this: “my_function”. If you’re working as a professional programmer, you have to use the method that everyone else in your company uses. However if you’re just coding for yourself, you can really use whichever you’d like… so long as you never. ever. use spaces in your function names.)
    Function names should always begin with lower-case letters, and they should describe what the function does – you wouldn’t want to name your function “header” (what does it do to the header?), but instead something like “getHeader” (this tells you the function gets the header).
  • Parentheses: You always must have the parentheses directly after the function name. When you have parameters to pass into the function, said parameters go between the parentheses. (What are parameters? Bear with me a moment more, and I’ll explain.) But even if you have no parameters, the parentheses must be there. Always.
  • Semi-Colon: Every expression in your code must end with a semi-colon. It’s kind of like the period at the end of a sentence – it signifies that you’re at the end of the expression.

Easy peasy, right?

Parameters

Sometimes you want your function just to give you something – like the getHeader(); function, which will always give you the exact same header every time you call it. This is normal, and a perfectly valid function. But what if you want to take something in, do something to it, and spit something else out? For example, (this is a super simplified example, bear with me) what if you wanted to take in a number, multiply it by 7, and then return the result?

That’s what parameters are for.

The function would look a little something like this: function multiplyBySeven($int) {
$int = $int * 7;
return $int;
}
So when you call the function, if you did this: multiplyBySeven(4); you would get back the number 28, or if you did this: multiplyBySeven(12); you would get back the number 84.

Those things between the parentheses are called parameters. A function does not have to take in any parameters, or it can take in many parameters, or it can even take in optional parameters. For example, you usually wouldn’t pass in any parameters into the getHeader() function, however if you look at the documentation for it, you’ll see that if you wanted to (and had reason to), you could pass in an optional parameter. Or take a look at our multiplyBySeven($int) function – that takes in one parameter.

So how do you know what parameters are supposed to be passed into a function? This is where the internet comes in handy, because there are far too many existing functions for me to explain all of them. If you’re wondering about a function defined by the default WordPress theme, all you have to do is search for WordPress and the function name. That should return a link to a page in the WordPress Codex, which is where the documentation for all the WordPress functions (and much more) exists. If it’s not there? Do a search for PHP and the function name, and you’ll likely get a link to a page within the PHP Manual. This is where much of the more general PHP documentation is. And if you still can’t find it? There’s a good chance it’s a custom function… so check in the files within your theme, like functions.php.

I’d Tell You More, But…

… goodness geeze, I’m long-winded. I was all ready to move on and explain why all those dollar signs are there in your code, but then I looked at everything I’ve already tried to stuff in your brain today and I realized I didn’t want to make anyone’s head explode.

But we’ve just barely broken the skin in our dissection of the infamous elePHPant so come back next week, when we talk variables and I have an itsy bitsy confession to make.

And if you ever have any coding questions, please don’t hesitate to ask! You can always leave a comment, or even email me… hey, maybe your question will even get its own blog post!

in Coding, PHP, Tutorial | Leave a comment

PHP: We’re going elephant hunting!

A rare sighting of the elusive elePHPant...
Photo courtesy of Phu Son Nguyen

There is an elePHPant in the room, and we really need to address it.

No, seriously.

Now, I don’t care who you are or what you say, but if you want a website that does more than just sit there and forever stay the same, we’re going to have to talk about this elePHPant. It goes by the name of PHP, and without it your website wouldn’t do jack. You want the same header on every page? You need PHP. You want comments on your posts? You definitely need PHP. Heck, you want posts that you don’t have to code by hand? Yep, you need PHP.

(Okay, okay, so technically you could do all these things using other programming languages. However you’d still need something beyond HTML and CSS, and PHP is by far the most widespread – and the one that you’ll see in every single WordPress website out there.)

PHP is an integral part of every WordPress theme. Without PHP, your website just wouldn’t work. You couldn’t have your newest posts show up on your front page every time you updated your blog; you couldn’t have the same header, sidebar, and footer automatically show up on every page. Nobody would be able to leave a comment, and an archive that lists all your posts? Forget about it.

Well, if I’m going to be up-front with you, you could have all those things (except for the comments). But you would have to re-code huge amounts of your website every time you added a new post, and if you have a business or a day job or just plain don’t want to spend all your time weeding through code when there are much better options… yeah, you don’t want to do that.

So. Now that we’ve decided that PHP’s an excellent idea for your website (any objections? No? Good.), it would be immensely helpful to understand what all that PHP code means, right? This is where my next few posts come in… I’m going to teach you everything you need to know. For now we’re going to ignore the functions.php file, which is where all the fancy schmancy PHP code goes, and just look at the basic PHP that you find in the rest of the files in your theme.

Come Out With Your Hands Up, PHP, We Have You Surrounded

If you look in most of the .php files in your theme, like index.php or sidebar.php, you’ll see that the PHP code is mixed in with the HTML code. So how does your browser know what to render as PHP, and what to render as HTML? Just as almost every HTML element has an opening and closing tag, so does PHP. The opening tag looks like this: The closing tag looks like this:?> Everything in between the opening and closing PHP tags is... you guessed it... PHP code.

There's really nothing more to it. Everything between those two tags is PHP code, everything outside is... not. Outside you usually have HTML, or even JavaScript sometimes, but anytime you ever want to include PHP in your code, it has to be surrounded by the <?php and ?> tags.

Ta Da!

So there you have it, your very, very basic introduction to PHP.

Wait... that's it?

Oh goodness no. In the next few weeks, I'm going to have a whole heck of a lot more to teach you about PHP. Believe me, we've hardly scratched the surface. But for now, I'm just going to leave you with today's short lesson, and let you digest that for a week.

Now would somebody please do something about the darned elephant crowding us all out of the room?

in Coding, PHP, Tutorial | Leave a comment

To Table or Not To Table? That Is The Question.

Should you really use a table?
Photo courtesy of Phu Son Nguyen

Imagine this scenario: you’ve decided you want a website, and you set out to code it completely from scratch (It certainly is possible–I’ve done it in the past–but with the great themes available these days, why bother? It makes so much more sense to let people like me help you).

You know you want the header at the top, a sidebar or two, the content in the center, and a footer at the bottom. So you go out on the internet, trying to learn how to code HTML, and you come across the <table> element.

“Well, that seems easy,” you think. “I’ll just use a table for the layout of my website! After all, a website is just one big table, right?”

Erm… not so much.

When to Avoid ‘Em

When I began learning web development several years ago, I was taught that no web developer worth their salt would ever use <table> elements for the layout of their websites.

EVER.

You’re supposed to use <div> elements and CSS instead. I realize that I’m biased, of course, towards the way I was taught and the way I’ve always done things. There are a lot of websites that use <table> elements for layout, so there must be some argument for them, right?

I want to bring you guys the best information possible, even if I have to accept that the way I’ve always done things is wrong, so I ventured out into the internet to research the arguments for and against table-based layouts.

Holy cow. There’s practically a religious war going on over the use of <table> elements vs. <div> elements for layouts!

In my sleuthing, I’ve discovered a few things:

  1. Most professional modern web developers use <div> elements for layout.
  2. All the web developers I’ve spoken with, some of whom are professional front- and back-end web developers at some of the top internet companies in the world, insist that you should always use <div> elements for layout.
  3. Most of the arguments boil down to this: if you don’t know CSS, <div> elements are a lot harder to use. But quite honestly, if you want a website and don’t want to learn CSS, you probably shouldn’t be the one coding your website. If that sounds like you, let ,e help you instead and I’ll take care of the <div> elements and the CSS.

So what makes <div> elements better than <table> elements for the layout of your webpage? Quite a few things, actually.

  • If you look at the table for a website developed using <table> elements, you’ll see that there’s two to three times as many lines of code as the same website developed using <div> elements. This might not make much of a difference to those of us on high-speed internet when we’re looking at regular websites, but for those many, many people still on dial-up, websites that use <table> elements will take forever to load. It just makes more sense to use the method that is most efficient so you don’t automatically exclude potential customers.
  • If you develop a website, you want the code to be easy to read and easy to edit. For you, first and foremost. If you ever have to go back and change something in your website (and believe me, you will), you’re going to want the code to be as easy as possible to read. With <div> elements, every <div> is essentially labeled (they all have ids or classes) so it’s easy to figure out what’s going on in your code. With <table> elements, especially once you start nesting tables to get the layout you need for your design, it can become very, very confusing. (CSS Zen Garden is a fairly good example of flexible coding. The HTML file is the same for every page there, but they each have a different CSS file, resulting in vastly different designs. It’s pretty interesting to look through to see the power of CSS.)

There is a single benefit to using <table> elements instead of <div> elements–vertical alignment. Using <div> elements, there is no way to vertically center elements in your layout. But with <table> elements, you can center things vertically. That single benefit from using <table> elements isn’t worth it for me, though. I’d rather have my <div> elements and just hack the vertical centering of elements.

So I’m going to tell you to use <div> elements for your website layout. Both because that’s what I always have and always will use, and because my research tells me that it’s the best option.

When to Use ‘Em

A lot of people nowadays are very familiar with the no-tables rule. But quite often, they assume it means no <table> elements ever. In reality, it’s completely logical to use <table> elements at the right time.

When you want a table, use the table element.

No, seriously! It makes perfect sense. After all, that’s what the element was intended for – to create <table> elements. <table> elements like this:

Banana Avocado Asparagus Potato
Fruit x x
Vegetable x x
Color yellow green green brown
Grown South America California California China

Don’t reinvent the wheel and spend hours or days trying to recreate an actual table using <div> elements and hoping everything will line up right. That’s just plain silly and a huge waste of your time.

Just remember any time you want an actual table in your website, use the darn <table> element. That’s what it’s there for.

Now That That’s Off The Table…

Next week, we’re getting hardcore. We’re going to look at PHP and get a very basic introduction to the language. You may not be ready to write the Google Algorithm by the end of it, but you’ll at least have a much better understanding of what all that PHP code in your WordPress theme means.

Remember: <div> elements for layout, <table> elements for <table> elements. Simple as that.

in Coding, HTML, Tutorial | Leave a comment

HTML: A Classy Identity

So Classy
Photo courtesy of Allison Day

If you look at the HTML code of any modern website, you’re likely to see a lot of <div> elements. A whole lot of <div> elements. A lot of coders use <div> elements to format the layout of their websites. But what does a <div> element do?

By itself, not much.

All a <div> element does is group the elements inside of it together, and add a line break after the closing tag. Seriously. That’s it. Nothing more.

Now, you’re probably wondering… why do we so often see <div> tags nested one within another… within another… within another? And how do we get from a <div> tag that supposedly doesn’t do much to a beautifully formatted website like CodeSwan where there’s obviously something more than mere grouping going on?

That, my friends, is the beauty of id and class attributes. They are a big part of how a website changes from a barebones scattering of elements to a beautiful work of art like the ones I do.

In essence, they are the bridge between your HTML and your CSS. They tell your browser where to apply the styles specified in the CSS file. And they’re not just for <div> elements. Anytime you want to apply some style to an element on your website, you’ll use an id or a class attribute.

Identify Yourself

Think of the id attribute as your Social Security Number. Every person only has one Social Security Number, and every Social Security Number only identifies one person (At least, that’s how it’s supposed to work). If you have one person with many SSNs, or one SSN that’s referring to more than one person, you know you have a problem.

It’s the same way with the id attribute. Every element should only have one id attribute, and you should only ever see each id attribute once in a webpage. Mind you, I said webpage, not website. If you look at the code here on CodeSwan or in most WordPress themes, you’ll see that almost every single page has an id=”header” attribute (or something similar). That’s okay, so long as you don’t see that attribute more than once on the same page.

One of the main reasons for using an id attribute in any of your elements is, as I mentioned before, to apply styles from your CSS file to your HTML code. Go look in your CSS file (probably titled something like ‘style.css’). Do you see how some of the words have a pound sign before them – for example, ‘#header’? That pound sign tells you that it’s referring to an id attribute (A period in front tells you it’s referring to a class attribute, and nothing at all means it’s a regular element, such as ‘body’ or ‘p’.).

Later we’ll go into all sorts of detail about your CSS file and how everything works, but for now you just need to know that the id attribute is used in conjunction with the CSS file to apply styles that you only want in one place on your webpage.

Another cool thing you can do with the id attribute is link to it to jump to the middle of a page. If you’ve ever followed a link in one of my blog posts to a previous post, you might have noticed that instead of going to the top of the post, the link jumps right to the part of the post that I’m referring to (Like here, when I was talking about the closing tag in HTML elements).

Notice how the URL is the link to the post, but then at the end it has a pound sign and then a name? (In that example, it was ‘#close_tag’.) That tells your browser that you’re jumping to that id in your webpage. Remember that there’s only one id in every page – so your browser is going to know exactly where it’s supposed to go. If there were multiple ids, then how would your browser know which one you’re referring to?

So remember: each id should only appear once on a webpage, and each element should only have one id.

Have A Little Class

Whereas the id attribute has a one-to-one relationship with your webpage elements, the class attribute has a many-to-many relationship. Each class attribute can have multiple elements, meaning it can show up as often as you need it on a single webpage, and each element can have many class attributes.

This comes in handy when you want to apply the exact same style more than once on a webpage. For example, take a look at our sidebar here on CodeSwan. Every single one of the boxes has the same design. If we only had the id attribute, then we’d have to create a new id every single time we wanted another box on the sidebar. And if we wanted to change something, we’d have to remember to change it for all of the ids, or else something might look a little screwy. That’d be a pain, right? (If this sounds familiar, it’s because we’ve said the same thing about using PHP to give every page the same header, sidebar, and footer without having to hard code it into every single webpage.)

Thus the beauty of the class attribute. You just have to create one class with the specific styling you want, and then add it to any element where you want that style. Even better, if you have several different classes that you want to apply to one element, that’s completely okay – just separate each class name with a space, like this:

This will tell your browser that it should apply three different classes to that <div> element: the ‘.comment’ class, the ‘.even’ class, and the ‘.highlight’ class.

Stay Tuned…

Next week we talk about the general layout of your website. This means we’ll discuss tables, when it’s okay to use them, and when to absolutely NOT use them (or else suffer my wrath, and the general disdain of any decent web developer out there). Believe me, you’re going to want to tune in for this one.

Even as we digress a bit the next few weeks, remember today’s lesson – every id should only be seen once on a webpage. But you can have as many instances of a class as you want.

So stay classy, my friends.

in Coding, HTML, Tutorial | Leave a comment