Blog

The four basics of PHP

Posted by battye in Modifications with the tags , , , , , , , , on November 21st, 2008

If you want to make a MOD and you just don’t know where to start, I think the best thing to do is to look at existing MODs to see how other MOD authors go about doing certain tasks. If looking at an existing .php file makes absolutely no sense, type a keyword of what you don’t understand into the search box on http://www.php.net – in many cases it will be a PHP function that will be well explained and documented.

For this blog post, I will address the four basics of PHP. Understanding these concepts will give you a kick start into the world of PHP and MODding.

“if” statement

The if statement is perhaps the most commonly used aspect of PHP. It checks whether a statement is true or false, and depending on the answer will or will not perform a certain task.

Suppose you want to output “Hello Ben!” but only if a persons name is Ben. In everyday language, it would look something like this:

Code: Select all
IF Name is 'Ben'
Output 'Hello Ben!'

For strings (ie. words, or letters, characters and numbers) it is marginally quicker to use single quotes than double quotes, hence it is ‘Ben’ and not “Ben”. The reason for this is that anything within double quotes, such as a PHP variable, can be evaluated, which means PHP is conciously looking through the string for anything it needs to process. This is unlike anything between single quotes which is taken on face value.

The “Else” and “Else If” statements are sisters of the if statement, and they can be used to output different results in various cirumstances.

Using the earlier example, say you had two people, Ben and Cephas, and you wanted to output the name of whichever person was chosen. In everyday language:

Code: Select all
IF Name is 'Ben'
Output 'Hello Ben!'
ELSE IF Name is 'Cephas'
Output 'Hello Cephas!'

Finally, if you had a dozen different people, but only wanted to say hello by name to only Ben or Cephas if they were chosen, you would use all three statements in this way:

Code: Select all
IF Name is 'Ben'
Output 'Hello Ben!'
ELSE IF Name is 'Cephas'
Output 'Hello Cephas!'
ELSE
Output 'Hello other person!'

The if and else if statements are only executed if the condition is true, while the else statement is only executed if the conditions above it were all false.

In PHP, the three code snippets above would look like this:

Code: Select all
$name = 'Ben';
if ($name == 'Ben')
{
echo 'Hello Ben!';
}
Code: Select all
$name = 'Ben';
if ($name == 'Ben')
{
echo 'Hello Ben!';
}
else if ($name = 'Cephas')
{
echo 'Hello Cephas';
}
Code: Select all
$name = 'Ben';
if ($name == 'Ben')
{
echo 'Hello Ben!';
}
else if ($name = 'Cephas')
{
echo 'Hello Cephas';
}
else
{
echo 'Hello other person!';
}

Note that any line that doesn’t have a statement or a curly bracket on it ends with a semi-colon. This is a convention of PHP to represent the end of a line, and missing a semi-colon will result in an error message. Using the word “echo” is telling PHP to output whatever follows, while “$name = ‘Ben’;” is the initialisation of a variable. Whenever you see a variable (a dollar sign before a word or set of characters, like $name, $var_1, $var_2, $var_test, etc) followed by an equals sign this shows that a variable is being set.

“while” loop

A while loop performs a task until a condition is false. For example, if you wanted to multiply the number 10 a total of 5 times (10×1, 10×2, … 10×5), it may look like this:

Code: Select all
number = 10
i = 1WHILE i <= 5
Output i * number
i = i + 1

Or in PHP:

Code: Select all
$number = 10;
$i = 1;
while ($i <= 5)
{
echo $number * $i . ‘,’;
$i++;
}

The asterix is the symbol used to multiply, while $i++ is another way of writing $i = $i + 1. By including . ‘,’ at the end of the echo line, it splits the results with commas, so the final output will be: 10,20,30,40,50,

In phpBB, a while loop will often be used in order to obtain multiple rows of data from a database.

“for” loop

A for loop is quite similar to the while loop, with the key difference being you can choose how many times the loop takes place and all variables can be defined and altered within the condition line.

The example above of displaying the multiples of ten can also be done using a for loop as follows:

Code: Select all
$number = 10;
for ($i = 1; $i <= 5; $i++)
{
echo $number * $i . ‘,’;
}

As can be seen, the $i variable can be initalised and the $i variable incremented within the one line.

Arrays

Once you know how to use if’s, while’s and for’s, the other major feature of PHP worthwhile knowing is the array.

An array stores many values within one main variable, so is useful for any kind of list, such as a list of songs.

You could create a list of variables, like this:

Code: Select all
$song_1 = ‘Vertigo’;
$song_2 = ‘City Of Blinding Lights’;
$song_3 = ‘Pride In The Name Of Love’;
$song_4 = ‘Miracle Drug’;
$song_5 = ‘Beautiful Day’;

But it is rather messy. It is much better to use arrays.

The most common ways of forming an array are as follows:

Code: Select all
$song = array(
‘Vertigo’,
‘City Of Blinding Lights’,
‘Pride In The Name Of Love’,
‘Miracle Drug’,
‘Beautiful Day’,
);

Or each array indice individually…

Code: Select all
$song = array();
$song[0] = ‘Vertigo’;
$song[1] = ‘City Of Blinding Lights’;
$song[2] = ‘Pride In The Name Of Love’;
$song[3] = ‘Miracle Drug’;
$song[4] = ‘Beautiful Day’;

To incorporate this into a for loop as above as a way of listing the five songs, you would do as follows:

Code: Select all
for ($i = 0, $total = sizeof($song); $i < $total; $i++)
{
echo $song[$i] . ‘,’;
}

sizeof() is a PHP function which counts the number of values within an array – in this case 5. By setting $i to 0 and looping $i for as long as $i is less than 5 (ie. running the loop when $i is 0, 1, 2, 3 or 4) each song can be listed by echoing $song[$i].

An array works by mapping a key to a value. By default (in the shortened form directly above) the key is a numerical value beginning at 0.

So for each array, the key 3 would map to the value Miracle Drug.

The key does not have to be numerical, it can be a string such as in these examples:

Code: Select all
$song = array(
’song_one’ => ‘Vertigo’,
’song_two’ => ‘City Of Blinding Lights’,
’song_three’ => ‘Pride In The Name Of Love’,
’song_four’ => ‘Miracle Drug’,
’song_five’ => ‘Beautiful Day’,
);

Or

Code: Select all
$song = array();
$song['song_one'] = ‘Vertigo’;
$song['song_two'] = ‘City Of Blinding Lights’;
$song['song_three'] = ‘Pride In The Name Of Love’;
$song['song_four'] = ‘Miracle Drug’;
$song['song_five'] = ‘Beautiful Day’;

Final word

If you want to test any of these examples yourself, paste a given PHP example into a text editor such as Notepad, and at the very beginning of the file add on a new line [i][/i] on a new line. The file can be named anything reasonable providing it ends with [i].php[/i] (so test.php, test1.php, my_test_file.php are all reasonable) and can then be uploaded to and run on any server with PHP installed.

For more in-depth analysis of each of the above aspects of PHP, please consult the php.net website:

IF: http://www.php.net/manual/en/control-structures.if.php
ELSE: http://www.php.net/manual/en/control-structures.else.php

ELSEIF: http://www.php.net/manual/en/control-structures.elseif.php
WHILE: http://www.php.net/while
FOR: http://www.php.net/for
ARRAYS: http://www.php.net/manual/en/language.types.array.php

26 Responses to “The four basics of PHP”

Posted by Dog Cow on November 21st, 2008 at 1:51 am:

“If you want to make a MOD and you just don’t know where to start, I think the best thing to do is to look at existing MODs to see how other MOD authors go about doing certain tasks.”

I disagree. The first thing these people ought to do is actually READ the phpBB Coding guidelines and keep them in mind. That’s the reason why we have so many awful MODs for phpBB 2. It is because these people copied the MODs of the people who DIDN’T read, so the whole practice of bad coding just propagates that way.

Posted by battye on November 21st, 2008 at 2:18 am:

Naturally reading the coding guidelines is a good place to start, but as far as looking at working examples and how you apply PHP to real life situations, you can’t go past viewing existing MODs.

Posted by Splitice on November 21st, 2008 at 5:46 am:

Just another way to do:
[code]<?php
for ($i = 0; $i < sizeof($song); $i++ )
{
echo $song[$i] . ‘,’;
} [/code]
This is bad because:
– count is executed on every loop.
– for statements are slow compared to foreach

[code][/code]
Its the most efficient way to do it in a loop (implode would be better)

The best way:
[code]echo implode(‘,’,$songs);[/code]

Posted by Abhishek on November 21st, 2008 at 6:25 am:

Is this all regarginf a mod ??
then coding guideline for phpbb would be great !!

Posted by Steven on November 21st, 2008 at 6:25 am:

Wonderful post for beginners Battye! <3 U2 😉

I’ve never written a mod (because I’ve never had a reason to, and someone else has probably already written one) but this was a great, simple refresher, really back-to-the-basics.

Posted by damsprivate on November 21st, 2008 at 8:45 am:

wow thanks
nice one it help me alot.

Posted by Drugs on November 21st, 2008 at 8:59 am:

Great article, helped me a lot.

And maybe you should change it to look at VALIDATED mods as examples. 😉

Posted by Emiel van Rossum on November 21st, 2008 at 10:26 am:

I really like this guide, because it is helpfull to me as a beginner!

Posted by jwxie on November 21st, 2008 at 11:28 am:

I remembered my beginning years even though i am not a great coder yet
i think when i was starting programming, loop was one of the problem
then all the sudden, array and object became annoying

Posted by jwxie on November 21st, 2008 at 11:31 am:

to Dog Cow,
for myself, i suggest as a beginning, they should first approach with the most basic php web coding
that is php+html
then they should move on the advance stuff like phpbb and its template engine system which is great because it’s default for phpbb

and yeah, the concept here is just to get some people started
without even knowing how to write some simple php + html is not going to help because they can barely understand the concept behind the engine
and of course,at the same time, they should start using phpbb and install some simple and medium or even advance mod so they get to see the common files a mod usually require to modify

Posted by c4gamerz on November 21st, 2008 at 12:49 pm:

Great article!! i hope this will give me a good start in the world of php 😀 Thanks…

Posted by Diet Ebola Cola on November 22nd, 2008 at 12:27 am:

Also, for someone that is completely new to php, Zend has an excellent PHP Tutorial here:
http://devzone.zend.com/node/view/id/627

Posted by Damian S on November 22nd, 2008 at 2:42 am:

This article was good, but should be altered to use count() instead of sizeof().
Not only is sizeof() merely an alias for count(), but more importantly, you are confusing C/C++ programmers new to PHP, since they are used to sizeof referring to the sizing in bytes of a datatype.

Posted by MartectX on November 22nd, 2008 at 5:25 am:

Nice article, but you violate the Coding Guidelines (http://area51.phpbb.com/docs/coding-guidelines.html#optimizing) yourself:

for ($i = 0; $i < sizeof($song); $i++ )
{
echo $song[$i] . ‘,’;
}

should be:

for ($i = 0, $size = sizeof($song); $i < $size; $i++ )
{
echo $song[$i] . ‘,’;
}

Posted by wGEric on November 24th, 2008 at 10:34 pm:

That for loop has been fixed. Thanks.

Damian S, phpBB’s coding guidelines use sizeof instead of count.

Posted by lin on November 27th, 2008 at 1:49 am:

thanks a lot for this article 🙂

Posted by joker400 on December 2nd, 2008 at 8:55 pm:

i think one of the problems are arrays is some how difficult to understand ….

thanks man for the tutorial .

Posted by legohalflife2man on December 2nd, 2008 at 9:06 pm:

This was a very good article. I can use it to reference to, in the future, when coding my websites in PHP. Thank you.

Posted by Eric Martindale on December 17th, 2008 at 4:09 pm:

Great post! This will be super helpful to refer to for all those phpBB newbies that keep asking me for help. :]

Posted by wolf2009 on December 30th, 2008 at 2:40 pm:

Thanks for this guide.

I have done some C++, not much just basics like this.

I have seen php codes like this for first time ( although I have added a lot of MODs to my forum ), and I am surprised how similar they are to C++.

Nice read btw !

Posted by Desdenova on January 2nd, 2009 at 3:43 pm:

wolf2009 – “I have seen php codes like this for first time ( although I have added a lot of MODs to my forum ), and I am surprised how similar they are to C++.”

There’s actually a reason behind it. 😉

If I remember right, PHP is coded using the C/C++ programming language (Can’t remember which one, though), so it only makes sense for the two languages to be similar. It also makes crossing between C and C++ to PHP and vice-versa much easier, unlike with that Microsoft junk known as ASP.. >.>

Posted by Lou-in-USA on January 3rd, 2009 at 2:38 pm:

Very good, but as someone with a few years of recreational programming experience I can say there are still plenty of coding practices in PHP I am not familiar with in PHP. The programming courses I took many years ago help keep most of my code tight and elegant but I see some pretty thoughtful coding practices that do in one line what I would use two or three line to accomplish! Learn from the experts. Read the installation details carefully, read the mods and back-up working code!

Posted by clea023 on February 15th, 2009 at 10:13 pm:

did the code boxes break during the hack/recovery?

the “code” I’m looking at looks like the html translation of normal code output…

Posted by Martyn on February 17th, 2009 at 4:28 pm:

All of the above comments are of worthy note, but I go back to the very first statement of this blog: [quote]If you want to make a MOD and you just don’t know where to start,[/quote]
This applies to more than just coding practices and standards. It has as much to do with how to locate the correct modules to modify when implementing a mod.
After much searching, you may find the ‘correct’ spot to add new fields into a form, but no idea where the validation code should be implemented, etc. A Guide that helps with this navigation would go a long way in folks over the initial insecurities of doing the job right.

Posted by wGEric on February 22nd, 2009 at 11:19 pm:

The code boxes did break. We’ll have to clean them up.

Posted by Robin on April 6th, 2009 at 5:10 pm:

Despite the code boxes being broken it still is an interesting article, keep it on phpBB team!

Commenting is disabled for this blog post