codeswan blog

HTML: An Intro To Headers

So you want to start putting together a website. Where do you start? Well, at the top, of course. The first thing anyone ever sees on your website is your header – so you want it to be great.

What goes into a good header? A good design, for one thing. A great logo, some nice fonts… a header that sets the tone for the rest of your website. But that’s not what I’m here for (believe me, you don’t want me designing your site!). The other important part of your header is the code – what makes your header actually work. And if you want to talk code… you know I’m your gal.

Head… Header… There’s a Difference, You Know

We’ve already discussed what goes in the <head> section of your website. And you know by now, that the <head> is not the same thing as the header. However, when you’re putting together your php files for your website, 99.99% of the time you’ll find the <head> of the website inside of the header.php file. It makes sense, right? The header.php file displays what’s at the top of every webpage, the <head> section is at the top of every webpage… so you might as well throw them together.

So you’ve got the doctype declaration up top, then the entire <head> section… and after that </head> closing tag, the <body> section of your website begins. This is where your header code starts.

Body First

So what comprises a header? Well, before it even starts, you have the opening <body> tag. Everything you see on your website is going to be inside of the body tag. So if there are CSS styles that you want on the entire website, then you can set them in your style.css file on the body tag, like this:body { background-color: #c0c0c0; } This just sets the background color of the body tag to #c0c0c0 (that’s the hexadecimal code for grey – more often than not, you will see hexadecimal codes used to refer to different colors on websites). Similar to how it is in PHP, you always need that semicolon at the end of each attribute, as well as the colon after the attribute name. Here the attribute name is ‘background-color’, and the attribute value is ‘#c0c0c0’. And since the <body> tag encompasses everything in your website, then the entire background will be set to gray. Think of it like your first coat of paint – you can add more paint on top of it, but the bottom layer will always be that color.

Backgrounds Are Important Too, You Know

Once you’re inside your <body> tag, what’s next? Well, let’s take a look at the header here on CodeSwan. If you look up top, you see that the first thing you see is the logo. There are a few things to take note of, regarding our logo. First of all, it’s really damn gorgeous. *nods* Yep. Heh… but we’re supposed to be talking about code here, aren’t we, instead of Son’s beautiful designs. *shameless grin*

First thing to note is that the logo is a link. That’s right, the entire logo. You can click anywhere on it, and it’ll take you to CodeSwan’s homepage. (Wait! Come back! There’s still more to talk about!) Second thing to look at is the image itself – no matter how big you make your browser, even if it spans the entire Vegas strip, the image will still go across the entire page – without getting all stretched out of shape. (Er, not that I’ve ever tried this. But it sounds nice. And hypothetically, it should work…)

But how do you get the image there in the first place? More often than not, especially if you have a fancy header like ours, you’re going to want to use a <div> element, and put an id on it. (Need a quick refresher course? Go back and check out my post all about ids and classes.) Let’s call this id “header”. So it ends up looking like this:

Now that’s great and all, but how do you use it to put in a header image? Why, CSS, of course. Yup, we use a background attribute again. But this time we’re referencing the id, not the tag name – it would be silly to reference ‘div’, because we’re going to end up with so many <div> elements in our code that our CSS isn’t going to have the faintest idea which one we meant, and therefore put the style on all of them. Which is certainly not something we want, at least not in this case. Nope, instead we use the id name, like this: #header { background: transparent url(images/header.jpg) no-repeat 0 0; } Hm. That looks kind of similar to the background that we put on the body… but there are a lot of differences.

First off, it just says ‘background’, not ‘background-color’. This is because we’re setting more than just the color. Where it says ‘transparent’… that’s the color. We could very well have put #c0c0c0 in there, or whatever color we’d like. But if we want the possibility of the layers of paint beneath the background to shine through (which certainly does happen, sometimes), then it’s better to just make it ‘transparent’. And sometimes you do want a different color on the background, and want to set it there instead of writing ‘transparent’… and that’s fine too.

Then it says url(images/header.jpg). It’s still part of the ‘background’ attribute, because we haven’t seen a semicolon yet. This tells your browser where to find the image that you want to use for your background. Usually in most WordPress themes, there’s going to be a folder inside of your theme called ‘images’, which is where every image you use in your theme should go. That way you can always use the path ‘images/imageName’ to tell the browser where your image is. (And don’t forget the extension! ‘.jpg’, ‘.png’, ‘.gif’… there are different situations for each, but you’ll probably see at least ‘.jpg’ and ‘.png’ images in your theme.)

Next, you tell the browser how that image should repeat. I used ‘no-repeat’, since I don’t want a tile that says “CodeSwan” repeating itself across the page. (I only want that logo image once, you see.) But if you do want it to repeat, you can use ‘repeat-x’, ‘repeat-y’, or ‘repeat’. Remember in high school math class, where the x-axis was the horizontal one, and the y-axis was the vertical one? It’s the same here. If you want an image to repeat horizontally you say ‘repeat-x’, and if you want it to repeat vertically then you set it to ‘repeat-y’. And if you want it to repeat both horizontally and vertically, then you just say ‘repeat’.

The last part of the background has to do with positioning. For my background, you see that I wrote ‘0 0’. Think about graphs once again, and you remember that (0, 0) was the origin. This is the same, except 0 0 is the top left-hand corner of your div. (For you math nerds, that would put us in the fourth quadrant, if I remember correctly.) Sometimes you’ll see values like ‘center center’, or ‘left top’… these do the same thing, except aren’t quite as exact. If you needed your background to be a little lower than how it started out, for example, then you could write ‘0 10px’ (Don’t forget the px! Otherwise it won’t work right.), or if you wanted it slightly to the right, then do (5px 0). Or any combination of the two.

When you’re setting the background attribute in CSS, remember that it always must go in this order: color, image url, repeat, position. If you mix things up, it’s very possible that your browser will get confused.

Little By Little

I think that’s enough for one day, wouldn’t you agree? It doesn’t seem like much – after all, we only really talked about backgrounds. But it’s quite important, and very useful. I use backgrounds all the time, and sometimes even for uses that you might not even think to use them for! They’re very, very handy.

So now that I’ve given you a little taste of what goes into a header – an appetizer, if you will – next week, we start in on the main course. After all, you don’t really think that I’m so mean that I would tell you about how our entire header is a link, or how it spans the entire page no matter how big, and not tell you how to do it yourself, do you?

No, of course not. But you’re still going to have to come back next week if you want to find out.

in Coding, HTML, Tutorial | Leave a comment

HTML: Head(er), Shoulders, Knees, and Toes…

For the last two months we’ve been talking about PHP. The month before that, we discussed tables, ids, classes, and other rules and concepts that are important for developing a website theme.

All of that is important, very much so. You couldn’t develop a website without it. However, what I have not yet explained is the actual body of the website – the part of the code that tells the browser what it’s supposed to show people who visit your website. Everything else is important, true, but this is the most important part of all.

And, well… to have a great website, you need a great body. Er… <body>. So in website terms… what makes up a good body?


Note that the header is completely different from the head of your website. The head goes at the very top of your code (right after the doctype declaration), and includes stuff like links to your CSS and JavaScript files, metadata, and other information about your website. None of which is actually displayed.

The header, on the other hand, is displayed. It’s what you see at the very top of just about every website out there. Here on CodeSwan, my header consists of our logo and my navigation bar. It’s exactly the same on every single page within my website.

Because the header is the same on every page in our website (and this holds true for most websites out there), we can use a single header.php file (go look! More likely than not, there’s already a header.php file in your theme) and just include it on every page we make in the website. Convenient, isn’t it?


As the name suggests, the footer goes at the foot – or at the bottom – of your website. As with the header, most footers are exactly the same on all pages – they usually include copyright information, sometimes an abridged version of the navigation, and can include other information such as who developed your website. And, as with the header, since it’s the same on every page in your website, you can just use one footer.php file, and include it on every page. Easy peasy.


The sidebar goes – you guessed it – at the side of your website. Now here’s where it gets a tiny bit more complicated. But don’t be scared. We can handle this.

The easiest scenario is when you have one sidebar that stays exactly the same on all pages. In this case, all you have to do is include a single sidebar.php file, just like with the header and footer. (Actually, that’s a lie. The very easiest scenario is when you don’t have a sidebar at all. But in that case, this section about sidebars doesn’t even matter, right?)

But then there are the cases when you have different sidebars depending on what page you’re on, or two sidebars next to each other, or one sidebar on either side of the content… this is where it gets a little more involved. In some of these cases, you’re even going to have to have multiple files for the sidebar.

But not to fear! I am here… and I am here for you. In upcoming weeks as we go through the body section of WordPress themes, I will explain this, all of this, and by the end of it you’ll be able to create sidebars like a pro.


Unlike the header, footer, and even the sidebar, your content section is going to be different on every page of your website. I mean it. Every single page of your website is going to have different content. (Because why on earth would you want two pages to look exactly alike? That’s just silly. Not to mention redundant and kind of pointless.)

So does this mean you have to have a different file for every single page on your website, since they all have different content? (If you have a blog, this can number into the hundreds, or even thousands.)

No, not at all.

*big sigh of relief*

You see, although the content on every page is going to be different, many of the pages have the same format. Take your blog posts, for example. Generally, blog posts consist of a title, the date it was posted, the author’s name, the actual post itself (consisting of words and pictures, usually), metadata, comments, and a comment form. And maybe some social media buttons and links to similar posts.

Every website is different, but within a website, every single blog post is going to consist of the same elements. So really all we have to do is make one .php file (usually single.php in your WordPress themes) that sets up the format for the blog post pages… and voila, all that’s left to do is insert the content for that particular blog post! Which is super duper easy. You won’t even break a sweat doing it. And… *drum roll, please*… you use PHP to insert the content, so you don’t even have to know which post the user is looking at! Your server does all the work for you. Ain’t it great?

Then there are other pages, like your About page (super duper easy), Archives page (easy), Contact page (a little harder, but plugins can help with this!), Shop page (also something plugins can make much easier… woo!), etc., etc…. depending on what’s in your pages, you can use the basic page.php template (like for the About page), or you can create additional templates that fit the format of your other pages. For example, here on CodeSwan I have one for my Archives page and another for my Contact page, since their styles are fairly different from my basic pages.

So there you have it, everything that makes up a WordPress theme!

Well… sort of. The rough outline, at least.

Next week, we really start discussing what makes up a website, as we look at all that comprises the header (not head! We already did that!) section of your website.

in Coding, HTML, Tutorial | Leave a comment

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.


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. 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 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. is another great resource. While is all about documentation, 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;
} else {
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 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 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.


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 (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.


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?


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 | 1 Comment