Basic PHP for People Learning WordPress: Variables, Arrays, Functions, and More

Posted OnDec 19, 2014     CategoryDevelopment     Comments1 comment

Whether you’re learning WordPress for a personal project, or you’re embarking on a path to become a theme developer you will benefit from learning PHP. This guide will set you off on the right foot with some beginner level PHP. These are the real basics, which you can put to use while customising WordPress. We’ll briefly discuss variables, basic arrays, functions and conditional statements as well as for and while loops. Throughout the guide there will be practical examples of how these techniques are typically used in WordPress.

Requirements

Before reading this guide, you should get to grips with the basic syntax of PHP. You should also have at least a basic understanding of HTML and know how to use a text editor to create .php files. To test your code you’ll also need a server that runs PHP. You can set one up on your local machine or get a basic unix hosting package to play with.


PHP Variables for Beginners

A variable is a self-defined handle for any value or set of values. In PHP, a variable is represented with a dollar sign pre-fixing the variable name. Names are case sensitive and can include letters, numbers and underscores. They must not begin with a number.

Example:

$my_variable

$this is a special variable, already used by PHP which you cannot assign values to. For more information take a look at php.net.

Assigning Values to a Variable

Values can be assigned in different ways, depending on the type of data your value is.

Strings

A string is a series of characters, like a sentence. The simplest way to assign a string to a variable in PHP is with single quotes:

$my_variable = 'A string of information';

When you look at your theme it is unlikely you’ll see strings assigned quite so simply. It’s good practice to set your theme up with localisation in mind, so it can be easily translated. What you’ll probably see is something more like this:

$my_variable = __( 'A string of information', 'theme_name' );

Integers

An integer is a numeric value. You can assign a number value by dropping the quotation marks like this:

$my_variable = 10;

You may see this in your WordPress theme:

$content_width = 637;

Other, more complex, types of values (like arrays and functions) can also be assigned to variables.


Basic Arrays

Very simply, an array is a list of values. Getting to grips with how different kinds of arrays work will give you a whole lot more control over your data. Values in an array can be easily manipulated and re-ordered. They will also be extremely useful when we move on to learning about for and while loops. The most basic form an array can take will look something like this:

$animal_sounds = array( 'Moo', 'Oink', 'Bleet', 'Meow', 'Wooooof' );

Each value in this array can be accessed easily with a numeric key. The keys begin at 0 on the left and go on from there. So, Moo is 0, Oink is 1 and so on.

echo $animal_sounds[4];

This would print:

Meow

Indexed Arrays

You can also specify your own array keys. This can be very useful for assigning meaning to each value, making it easier to see what’s going on in your code.

$animal_sounds = array(
    'cow' => 'Moo',
    'pig' => 'Oink',
    'sheep' => 'Bleet',
    'cat' => 'Meow',
    'dog' => 'Wooooof'
);

Each animal sound value in the array above has now been given a key, which is the animal’s name. The values can now be accessed like this:

echo $animal_sounds['pig'];

This would print:

Oink

Arrays Inside Arrays

So, what if you want to assign more than one sound to each animal? This is where it would be useful to have arrays inside arrays. You can do just that. These are called multi-dimensional arrays and they’re a common site within WordPress functions and themes. So, for example:

$animal_sounds = array(
    'cow' => 'Moo',
    'pig' => 'Oink',
    'sheep' => array( 'Bleet', 'Baaah' ),
    'cat' => array( 'Meow', 'Puuur' ),
    'dog' => 'Wooooof'
);

Here we’ve added multiple sounds for ‘Sheep’ and ‘Cat’. Here’s how you’d access the values in the example above:

echo $animal_sounds['sheep'][2];

Notice the array key which is a string is wrapped in quotes. It’s important to make this distinction, always using quotes where strings are concerned. The statement above would print:

Baaah

If you wanted, you could go crazy and add more arrays inside the arrays which are already inside the array.

Arrays in WordPress

Here is a simple example of an array you are likely to see or use in your WordPress Theme:

add_theme_support( 'post-formats', array( 'aside', 'audio', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video' ) );

It sets a group of values, defining the post formats which the theme supports. You may also come across more complex arrays, for example: when registering custom post types.


An Introduction to Functions

A function is a group of statements that together perform a re-usable task / set of tasks. You define a function like so:

function my_function(){ /*Statements will go here.*/ };

So, to demonstrate, you could write a very simple function which just returns some information like this:

function make_noise(){
     return "Meow";
};

Now you can call the function elsewhere in your code like this:

echo make_noise();

Which will print (you guessed it):

Meow

Let’s make this more useful.

Function Arguments for Beginners

Functions can be passed extra information to use. This is done through lists of variables called arguments. For example:

function make_noise( $animal = 'cow' ){
  $animal_sounds = array(
    'cow' => 'Moo',
    'pig' => 'Oink',
    'sheep' => 'Bleet',
    'cat' => 'Meow',
    'dog' => 'Wooooof'
  );
  return $animal_sounds[$animal];
};

Here we’ve set up one argument for our function so we can pass it a different animal parameter each time we call it. We’ve also set a default value so we don’t need to pass any parameters if we don’t want. We can put the function to use like this:

echo make_noise();
echo make_noise( 'cat' );
echo make_noise( 'dog' );

In turn, these will output:

Moo
Meow
Wooooof

Built in Functions

As well as being able to define your own functions, both PHP and WordPress also have a whole boat load of built in functions you can make use of. Take a look at the PHP Manual and the WordPress Codex to find out more. You can look up any functions and find out all about them. Here are a few to get you started:

Some Useful PHP Functions

Some Useful WordPress Functions

 


Control Structures for Beginners

Control Structures are a fundamental part of any programming language. They are the constructs that allow you to add fine control over your statements and functions, applying logic throughout your code. The most important to learn at the beginning is if.

If, Elseif and Else Explained

The if construct allows you to conditionally execute portions of your PHP code. It’s really best explained with an example. To create your own if construct, here’s how you’ll begin:

if ( /* Your expression goes here*/ ) {
     /*The statements to execute go here*/
}

Your expression will be what you’re checking for. It’s the requirements that the code inside your curly brackets needs to run. For example:

if ( $input = 'farm' ) {
     /* These lines will only run if $input contains the string 'farm'. */
     echo make_noise('cow');
     echo make_noise('pig');
}

You can take this further and add other expressions for what happens next too.

if ( $input = 'farm' ) {
     /* These lines will only run if $input contains the string 'farm'. */
     echo make_noise('cow');
     echo make_noise('pig');
     echo make_noise('sheep');
} elseif ( $input = 'domestic' ) {
     /* These lines will only run if $input contains the string 'domestic'. */
     echo make_noise('cat');
     echo make_noise('dog');
}

But what if none of the expressions you’ve checked for are true? That’s where else comes in. It’s like a catchall.

if ( $input = 'farm' ) {
     /* These lines will only run if $input contains the string 'farm'. */
     echo make_noise('cow');
     echo make_noise('pig');
     echo make_noise('sheep');
} elseif ( $input = 'domestic' ) {
     /* These lines will only run if $input contains the string 'domestic'. */
     echo make_noise('cat');
     echo make_noise('dog');
} else {
     /* This line will only run if $input contains neither 'farm' or 'domestic'. */
     echo "Rooooar!";
}

You’re not limited to using equals either. There are a loads of comparison operators to choose from.

It’s also worth noting that when your statement inside is only 1 line long, you do not need to wrap it in curly brackets. For example, the following is completely acceptable:

if ( $input != 'farm' && $input !='domestic' )
     echo "Roooooaar!";

Alternate Syntax

It’s common in WordPress to see if constructs written in an alternate syntax.  What you might find are conditional constructs written like this:

if ( $input = 'farm' ) :
     /* These lines will only run if $input contains the string 'farm'. */
     echo make_noise('cow');
     echo make_noise('pig');
     echo make_noise('sheep');
elseif ( $input = 'domestic' ) :
     /* These lines will only run if $input contains the string 'domestic'. */
     echo make_noise('cat');
     echo make_noise('dog');
else:
     /* This line will only run if $input contains neither 'farm' or 'domestic'. */
     echo "Rooooar!";
endif;

They work exactly the same way, they just look a little different. Notice how the curly brackets have all been removed? Instead, colons are used after expressions and the entire construct is ended with the endif statement.

A Practical WordPress Example

One really common use for if constructs in WordPress is to conditionally load scripts and styles.

if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
     wp_enqueue_script( 'comment-reply' );
}

The example above uses lots of built-in WordPress functions (check the codex if you want to find out what they all do). The expression checks if the page is a single post, if comments on the post are enabled and if threaded comments are switched on. Only if all of these things are true will the comment-reply script be enqueued.


Still with Me? That’s all for part one. We’ll go be going over some more control structures in Part 2, which will explain the different kinds of for and while loops you are likely to encounter in WordPress.

1 comment

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Send this to friend