I get a lot of questions from people about WordPress. Whether about themes or my plugins or even more esoteric queries they continue to roll in. Unfortunately, my answer rate has somewhat dropped. Either the question has already been asked and answered, the question is asked in such a way — or in a place — that I don’t understand it, or the question is, frankly, nuts. As such it occurred to me that what might be most helpful is to help people help themselves. Trite and clichéd as it may be, it’s still a worthwhile endeavor if for no other reason than to assuage my guilt at not responding to questions.
This will start off rather basic, as some people seem to need it. If you are not that person, skip on down.
Click on the link to continue to the whole story. No, I’m not doing this for pageviews but rather because this will be loooong and I don’t want my front page taken up with it.
Table of Contents
Here’s a table of contents so you can decide whether this part will be worth your time. If not, perhaps Part 2 will be.
- What is PHP?
- How do I start?
- A bit of insight about PHP
- Things are only variable when they’re not constant
- If only I could have conditionals, then…
- With the appropriate building blocks, one can construct anything
- We loop because we care
- An array of interesting possibilities
- Finishing things up… a look ahead to the future
What is PHP? (back to TOC)
PHP is a language most commonly used in web development. WordPress itself is developed in PHP. WordPress plugins are also written in PHP. PHP is not a difficult language and is quite similar to C and even C++ if you have experience with those. PHP has a feature-rich interface and extensions to do everything from database access to graphics drawing.
How do I start? (back to TOC)
There are a few ways to work with PHP code. The most common way is to create a file that ends in a “.php” extension and stick it up on your web server. This will almost certainly work especially if you have a working WordPress installation already. If you don’t and trying to load a file with that extension doesn’t behave correctly you may have to get cuter and edit your .htaccess file. Stick this in your .htaccess file in the root of your web directory:
[code]AddHandler application/x-httpd-php .php[/code]
Now you should be good to go.
Some people like to embed PHP code directly in their HTML files. This is fine too, but you’ll have to perform some similar magic in the .htaccess to get Apache to execute the PHP in “.html” files. Stick this in there and you’ll likewise be golden.
[code]AddHandler application/x-httpd-php .html[/code]
Now we’ve got Apache ready to process our PHP code, what do we put in it? Try this to start. (You can pull up this example in a source file here and you can see the resulting output here.)
[code lang="php"]
[/code]You might be saying to yourself “that looks a whole lot like HTML” and you wouldn’t be wrong. One of the most beautiful things about PHP is the ease of integration within HTML and this example was written expressly to show this ability. At the top there you see a fairly standard HTML page. You can write entire pages of HTML code in a PHP file and it will function just as you’d expect. It’s only when we hit the PHP delimiters that something different happens. But what?
A bit of insight about PHP (back to TOC)
This will be a simplified explanation that will take some liberties with the actual process but it will work as an illustration of the activity for our purposes. PHP can be thought of as an actively parsed language. Once that delimiter, <?php, is hit, the PHP module within Apache starts executing that code so that PHP code itself is never actually sent out to the browser as text. Only what the code actually outputs is sent. In this example, following the <body> line, the PHP delimiter <?php is found and the code within is executed. In this case we have an echo statement, a fairly simple but powerful tool that sends its output to the user’s web browser. This particular echo invocation sends the string literal “Today is” to the output buffer. The next part, a period followed by a date() function call, means that we’ll append a textual representation of the date to the text string that we’re sending out.
What the browser receives when it finally receives this output is the following (but only if you happen to be viewing this page on a Wednesday which is the day on which I’m writing this, otherwise it’ll be whatever day on which you’re reading this):
[code]
Today is Wednesday[/code]
Hey! That looks like HTML! Good catch, that’s exactly the point. What gets sent to the browser is indistinguishable from static HTML, except now we’ve made it rather dynamic. I’m sure you can see the power inherent in this and can think up plenty of uses even for this simple example.
Things are only variable when they’re not constant (back to TOC)
My own site has several that are quite simple like this. If you’ve ever left a comment on my site, the sidebar will welcome you back (see here for a sample image). That’s slightly fancier because I also use my Image Headlines plugin to render the text but the principle is the same. To just print the name of the person visiting your site (given that they’ve left a comment), we’d do something like this:
[code lang="php"]
Welcome Back,
[/code]
What’s that? That thing starting with a dollar sign is a variable in PHP. Variables are exceedingly straightforward in PHP. They don’t have to be declared before use and they can assume any type. In this case on my site, $comment_author is a variable that holds a string representation of the name of the visitor to my site as gleaned from some built-in WordPress cookies. I have to do a bit of work to make sure that the variable is populated, but that’s a subject for a different part of this tutorial. Just have faith right now that $comment_author contains the name of the visitor. In fact, let’s explicitly set it to a cutesy name so we can see how we perform assignments to variables in PHP (here is the source and here is the output).
[code]
Welcome Back,
[/code]Note how we can sprinkle PHP and HTML together rather easily. After our <body> declaration we create a variable called $comment_author and we assign to it a string with the value FearlessReader. Anywhere we reference that variable — as in the echo that follows shortly thereafter — we’ll actually produce the value of the variable which is now FearlessReader. You can likely predict the output to the web browser, but I’ll tell you just the same.
[code]
Welcome Back, FearlessReader
[/code]If only I could have conditionals, then… (back to TOC)
Much of the power of programming in all forms comes in the form of conditionals. A “conditional” means that we’ll do one thing if a certain condition is true and we might do something else if the condition is not true. PHP provides a full suite of conditionals to play with. The obvious and most straightforward is the “if something then do something” case. Let’s start with a simple example and then do one that a lot of people have asked me about (here is the source for this example and here is the output).
[code lang="php"]
You are a wise sage for using Firefox.
<?php } else { ?>
You are a silly person for not using Firefox.
<?php } ?>
</body>
[/code]
There’s so much good here I hardly know where to begin.
“At the top, dolt.”
Yes, as good a place as any. We’re getting a bit more complex now and I’m introducing some heavy concepts in this example but you’ll be happy and content once you understand them. Let’s start with that first PHP line. We have our conditional, if ( expression ). That line says that if what is contained in the parentheses is true then the following “code block” is executed. We’ll come back to that “code block” concept in a bit and introduce a useful component of good practices when we do, but let’s look at the expression within the parentheses a bit before that.
Here’s the expression: strpos($_SERVER['HTTP_USER_AGENT'], ‘Firefox’). That looks complicated and it is a bit tricky so don’t be dissuaded. First, strpos() is a function in PHP. Suffice it to say that functions perform some action given some information and optionally return some other information. This particular function takes an input string as the first parameter, in this case $_SERVER['HTTP_USER_AGENT'] which I’ll get to in a minute, and a string to try to find within the first string, in this case 'Firefox' and it will return the index within the input string of the first character of the first appearance of the second string. Confused? Consider it this way: if the input string happens to be "I really like Firefox", then the index returned by strpos() will be the numeric index — starting from zero — of the F in Firefox or, in this case, 14. If the search string is not found in the input string, a boolean value of false is returned from the function. This will likely be a confusing matter for some C and C++ programmers — who are used to a value of zero being functionally equivalent to boolean false — at first but you’ll get used to it.
Let’s revisit the first input string now, the variable $_SERVER['HTTP_USER_AGENT']. Browsers, when requesting pages from web servers, will send a bit of information about themselves. Among this information is the “user agent string” which is a fancy way of saying “the kind of browser it is”. User agent string are some of the least documented and most callously abused items by browser developers and they will throw stuff in there that truly makes no sense. But, the key part is that every Firefox browser ever written will include as part of its user agent string the word “Firefox”. I know, how kind. So, your browser sends this information to the server. Your server, when executing your PHP code, kindly populates some built-in variables for your use. These take many forms, among them an array — and we’ll come back to arrays more later — containing useful environmental information like the reported browser user agent string. The variable $_SERVER['HTTP_USER_AGENT'] allows code written in PHP to access the browser’s reported user agent string. For instance, here’s what my user agent is reported as: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7. Note the “Firefox” in there.
(Note that there is a load of similar information available to PHP scripts. See here for more information about everything available.)
So, applying what we know of the strpos() function, the code in our conditional expression is going to search the user’s reported user agent string and find the first instance of the string “Firefox” and return the index to that instance. Dandy. Our strpos() call will return either a boolean value false if the string doesn’t contain the word “Firefox” in it (if, for example, you are using Internet Explorer) or some numeric index that isn’t a boolean false if the string does contain the word “Firefox” in it (as in my case). So, let’s take my case. I am using Firefox so the strpos() function will return some index that we really don’t care about aside from the fact that it exists. The return value is therefore not false so let’s substitute the value true in our conditional to approximate that:
[code lang="php"] [/code]
Well that’s pretty easy! It’s practically English at this point so read it: “if true”. In other words, if the user agent string contains the word “Firefox” in it somewhere, we’re going to do the stuff in the immediately following code block. In this case, we’ll praise the intelligent person for using Firefox.
I did a little more than what I said I would… overachieving as usual. You’ll note that there’s a bit more there and, given what we’re already learned you should be able to tell what it does. It’s this part.
[code lang="php"]
You are a silly person for not using Firefox.
<?php } ?>
[/code]
We have the PHP delimiters, some squiggly braces and an else clause. It shouldn’t surprise you to know that the else means “do the stuff in the “code block” below if the condition in the initial if expression is not true.” In pseudocode this entire if...else clause would read:
If the user is running Firefox then print a good message. Otherwise, print a snarky message.
PHP provides one additional type of conditional clause that’s very useful, the elseif clause. This essentially allows us to string a succession of conditional expressions, testing them one by one. Take a look at this example (source here and resulting output here). I won’t go through it line by line as, by now, you should know what to expect.
[code lang="php"]
You are a wise sage for using Firefox.
<?php } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ) { ?>
You are especially silly for running Internet Exploder.
<?php } else { ?>
You are a silly person for not using Firefox.
<?php } ?>
</body>
[/code]
With the appropriate building blocks, one can construct anything (back to TOC)
I’ve talked about “code blocks” on more than one occasion. What does that mean? PHP and most other modern languages has concepts of blocks of code. In PHP, curly braces are the delimiters of code blocks. What does this mean? Let’s look at a quick example.
[code lang="php"] [/code]
We’re declaring two variables, $text_color and $background_color and setting them to some default values. We’re then going to have a conditional that checks if the $comment_author variable — we’re assuming it exists at this point as in the above example — is set to my name. If so, we’re going to change the value those variables have so that we can use them to, for instance, make my comments a different color. Everything in between the curly braces is considered a part of the “code block” that will execute if the expression in the conditional evaluates to true.
Given all that, what’s the difference in the following code?
[code lang="php"] [/code]
Looks pretty much the same. In fact, there’s a large difference between the two and this is a common mistake among programmers. Note that the only visible difference between this example and the preceding example is we’ve removed the curly braces. In this code, the behavior is the same until you consider what gets executed when the expression in the if conditional evaluates to false. In this case, the $background_color variable gets set to “#EECCCC” regardless of the result of the conditional expression check. Only the first line following the conditional statement — the $text_color assignment — is a part of the code block for the conditional since there is no curly brace. In situations like this, that first line is the code block.
Put another way, indents are like Dubs: they may look nice but they don’t do shit. That’s why it’s good practice to always surround code blocks with curly braces even when you only intend to have a single statement execute.
So we know a bit about code blocks. We know a bit about our conditional. We’re making some decent progress. Let’s look at another construct that will be of some use.
We loop because we care (back to TOC)
Ah loops. Loops are what they sound like: blocks of code that get executed some number of times. There are several looping constructs available in PHP. Let’s start with a straightforward one (source here and output is available here).
[code lang="php"]
echo "<li>This is item number $i.</li>";
$i = $i + 1;
} while( $i < 5 );
?>
</ul>
</body>
[/code]
This is… fairly useless. It’s illustrative, though, so bear with it. We start by declaring a variable, $i, and assigning it a value of the integer 1. Then comes the beginning of our loop, starting with do { and ending in } while( ... ). This is known as a “do… while” loop for fairly obvious reasons. We will do the stuff between the opening and closing curly braces while the expression in parentheses (in this case, while the variable $i is less than the value 5) evaluates to true. Makes some sense, no?
The stuff in the curly braces shouldn’t be too surprising aside from one detail that again exemplifies the power of PHP. Take a close look at our echo statement. We’re echoing out, or outputting to the browser, a list item with some text in it including what looks like the string $i. Take a look at the output, though. We’re actually outputting the value of the variable named $i and we’re doing it within the bounds of the double-quote. The double-quote in PHP is a bit of magic, because any variables found within it (with some esoteric exceptions) are evaluated and the value is printed instead of the literal string. If we had instead used single-quotes in that echo statement, we would get this output. Snazzy, eh?
The final line inside the curly brace simply increments the value of the variable $i, by taking the current value and adding one to it then assigning it back to the variable. Yes, C programmers, there’s the same host of pre- and post-increments and decrements available but that’s mere icing for those of you new to PHP.
There are many, many looping constructs available in PHP. I’ll quickly iterate them and briefly explain them so you know what they are. It shouldn’t be hard to apply what you already know to these new constructs as they typically merely iterate in subtly different ways.
Given what we know about the “do… while” loop, what do you think a “while” loop does? Precisely the same thing — execute the code in the code block between the curly braces while the expression is true — but instead of testing the expression after executing the code, it tests it before executing the code. (Here’s the source, here’s the output.)
[code lang="php"]
echo "<li>This is item number $i.</li>";
$i = $i + 1;
}
?>
</ul>
</body>
[/code]
Another looping construct is the “for” loop. The syntax is a bit weird but the idea is similar to the while loop and is truly interchangeable with it. Consider it a bit of a shortcut. (Source is here and output is here.)
[code lang="php"]
echo "<li>This is item number $i.</li>";
}
?>
</ul>
</body>
[/code]
Note that we’ve gotten rid of two lines in comparison with the preceding two examples: we got rid of the $i = 1 where we initialize $i to be 1 and we got rid of the increment. That’s because we did them in the for loop! Here’s how to look at the for loop: for ( statement that runs before the first test of the expression; the expression we'll test before executing the code in the curly braces each time through the loop; a statement executed at the bottom of the loop every time we go through the loop).
There are a few more constructs that could be considered loops — just as there are additional constructs that could be considered conditionals — that we won’t look at in this part of the tutorial. We have to save something for next time.
An array of interesting possibilities (back to TOC)
I mentioned arrays before and I’d be remiss if I didn’t introduce them to you in some fashion in this part of the tutorial. So far, aside from the $_SERVER variable mentioned above, we’ve been dealing with what are referred to as “scalar variables” or, if you prefer, “flat” variables. They have a type and they have a value. We used $comment_author to store a string, we used $i to store an integer. What if I have many things to store? What if, purely hypothetically, I wanted to have a collection of the comments from one post on my site? That’s many different strings (actually, many different disparate pieces of information including a string for the comment itself, a string for the author name, a string for the author email, an integer for the comment ID… you get the point but for the purposes of this discussion we’ll just assume we only mean the comment text). We obviously can’t store all of these different comments (easily) in a single string. We need something more.
Arrays to the rescue. Arrays can be thought of as a collection of items. We can have an array that contains all of the comments in a post, each as separate elements of the array and independently accessible. Let’s look at a very simple example (source here and output here).
[code lang="php"]
for( $i = 0; $i < count( $my_array ); $i++ ) {
echo "<li>Array item number $i contains '$my_array[$i]'.</li>";
}
?>
</ul>
</body>
[/code]
This is an utterly contrived example, as we’re simply creating our array and then iterating over the elements, but again it’s for illustrative purposes. Typically our array will be populated elsewhere.
So, those first three lines starting with $my_array are creating an array of that name and adding three elements to that array. This is rather powerful in relation to other languages with which you may be familiar as the array doesn’t need to be allocated ahead of time with a static amount of space. The mere act of assigning a value to an element of the array suffices to, first, create the array itself if it doesn’t exist, and to add space for a new element to hold the thing we’re assigning. So, we assign 3 elements to that array, accessible at the keys 0, 1 and 2. Next, we use a for loop to iterate over the elements and print both the key and the contents found at the index. We can access an element by specifying the array name and the key we wish to access, e.g. $my_array[0] accesses the first element in this particular array.
Now, watch how nutty this gets (source here and output here).
[code lang="php"]
-
$my_array[] = 3.1415;
foreach( $my_array as $key => $value ) {
echo "<li>Array item key $key contains '$value'.</li>";
}
?>
</ul>
</body>
[/code]
Sweet mother of avarice, what the hell is that? This is such a hot example I get all tingly. Let’s see the output:
[code]
- Array item key 0 contains ‘This is the first element.’.
- Array item key a number contains ‘8675309′.
- Array item key 1 contains ‘3.1415′.
There are a few things I wanted to show in this example. First: array keys can be either integers or strings. Or both! PHP doesn’t much care. Now, it’s probably not good programming practice to use both in a single array but it’s awfully fun seeing that it’s possible.
The second important thing to note is that the value of any particular element in the array can be any PHP data type. I’ve got strings, integers, and floating point numbers in there and PHP is content with that. You can have each element of an array be an entire other array. How powerful is that?
The third thing is how I assigned the third element in my array. I did this: $my_array[] = …. This can be thought of as assigning the element to the next available integer key in the array. It is not guaranteed to be anywhere in particular in the array — in this case it ends up, as the output above shows, at key 1, but that’s not guaranteed — and so you shouldn’t access it via any particular explicit key. So how do you get to it? That’s covered in the next important point.
I want you to notice how I accessed the array elements this time. Since each of my keys was a different type — and the final key was automatically generated for me — I need a way of simply accessing the elements of the array, regardless of which key is used to access it. The foreach construct of PHP was made solely to access elements of an array. Let’s look at it again: foreach( $my_array as $key => $value ) {. Foreach is quite similar to a for loop. It will iterate over every element in the array, and once inside the associated code block, the $key variable will hold the appropriate key and the $value variable will, perhaps unsurprisingly, hold the value of the element. This is one of the most useful constructs in PHP and you will see it used a ton in most PHP scripts, including WordPress.
Finishing things up… a look ahead to the future (back to TOC)
We’ve covered a lot of ground and read a lot of words, but we’re only scratching the surface. We’re building a foundation of knowledge here that, while immediately useful in very basic ways, opens many doors for more complicated endeavors in future Parts. Stick with it! Here’s some of the things we’ll talk about in one of the next parts.
- The pain and suffering of global scope
- Other useful conditionals and loop constructs
- Forms and their unhealthy attraction
- Regular expressions of angst and doubt
- Interfacing with MySQL
- Output buffering for success and profit
- WordPress tricks and innards… getting dirty
- “Where dem graphics at, Ma?”
See you next time!


