PHP: Back to basics - Part 3

So I'm back with my Back to basics series of posts. In part 1, we dealt with what PHP is and how it works and in part 2 we dealt with the very basics of variables and functions. Now in most programming tutorials, you'll usually deal with variable types, control statements, loops and the such (we're getting there), before you do functions, but because of the way PHP works and the way it sets its' variables, I decided to do basic functions before everything else.

In this post, we're going to take a closer look at variables and then we'll move onto control structures, loops and how variables are evaluated.

Variables

I'm trying to think of a way to explain variables from the start so people don't get confused straight off the bat. Truth be told, there are quite a few types of variables, but we'll group them into 3 distinct types:

  • Strings
  • Integer Types
  • Containters

We'll deal with Strings first as they're the easiest to work with at first and if you've gone through part 2, you've already had exposure to them.

Strings

Strings are pretty much your bread and butter when it comes to outputing data. If you're using PHP to build web pages (which is probably likely), you're going to be outputing alot of data to the browser. Everything that you want to output, will be converted to a string, be it characters, numbers, punctuation, basic bullets. If it's in the ASCII table, it can be a string.

This is how you assign a string a variable:

<?php
$mystring = "This is a string!";
echo $mystring;
?>

You guessed it, this outputs This is a string!. Easy stuff, but we've coverd this before, so it shouldn't be too hard to grasp. You can concatenate two strings together (combine them) by simply placing a period between the strings. Here's an example:

<?php
$mystring = "This is a string!";
$mystring = $mystring . " This is a string which we've concatenated onto the end.";
echo $mystring;
?>

This should output the following to your browser:

This is a string! This is a string which we've concatenated onto the end.

You can do the same thing as above in a shorter manner. When you have a variable that contains data in it already and you want to assign more data to that variable, but you want to concatenate it together, you can put the concatenate processor (the period) before the equals sign and then drop the second use of the variable. This is how the above looks, but in the short hand version:

<?php
$mystring = "This is a string!";
$mystring .= " This is a string which we've concatenated onto the end.";
echo $mystring;
?>

You can also insert special characters into a string like a line feed (new line) "\n" or carriage return (enter key) "\r"; I mention this now because I need to explain that there are two ways of assigning a string to a variable. When you have a string with a line feed in it ("\n") and you output the string to the browser, you won't see the "\n" string as you see it now on the screen. Instead it translates it to a new line and outputs that. The best way to explain is to show you I suppose.

<?php
$html = "<html><body>This is some test html</body></html>";
echo $html;
?>

You should see the following on the web page:

This is some test html

If you right click in your browser and "View Source", you should see the following:
<html><body>This is some test html</body></html>

As you can see it's one long line of html. If you're generating alot of HTML code, assigning it to variables and then outputting those variables to the browser, it could make for some very messy looking code.

What we want to do is format our code so it becomes more readable. By simply adding line feeds to our strings, it will make our life much simpler.

<?php
$html = "<html>\n<body>\nThis is some test html\n</body>\n</html>\n";
echo $html;
?>

What you will see in the browser is exactly the same as last time, so I'm not going to bother with that. When you view the source code again however, it will look like this:

<html>
<body>
This is some test html
</body>
</html>

As you can see, this is way more readable.

You can also "embed" (embed is probably the wrong word, but I can't think of a better one) variables in strings. Lets say you get a value from an external source, like a database and you want to insert that value into a string. You could concatenate the strings together, or you could embed the value in the string. Here's an example:

<?php
	$dbvariable = "Jimmy"; // Pretend this came from the database
 
	echo "Users name: ".$dbvariable."<br>\n"; 	// Here we've concatenated the strings
	echo "Users name: $dbvariable<br>\n";		// Here we've embedded the string
?>

The following should come out in your browser:

Users name: Jimmy
Users name: Jimmy

As you can see they do exactly the same thing.

Anyway, I'm getting slightly off trackhere. As I said earlier, there are two ways of assigning a string. The way we have been doing it so far is with the double quotes ("), but you can put strings in single quotes ('), but there is a difference though.

When you assign a string with the double quotes, the contents of the string is evaluated. If there are any variables in the strings, or special characters like line feeds and such, they are converted into what you would expect them to be converted to.
When you assign a string with single quotes however, the string is assigned literally and nothing is evaluated, so it's "what you see is what you get".

The best way is to just show you. We'll use the example from earlier where I showed you how to embedd a variable into a string, but this time we will use single quotes for all our strings:

<?php
	$dbvariable = 'Jimmy'; // Pretend this came from the database
 
	echo 'Users name: '.$dbvariable.'<br>\n'; 	// Here we've concatenated the strings
	echo 'Users name: $dbvariable<br>\n';		// Here we've embedded the string
?>

The following should come up in your web browser:

Users name: Jimmy
\nUsers name: $dbvariable
\n

As you can see, with the sinle quotes, the "\n" isn't translated into a new line and the variable $dbvariable isn't converted into the value it contains within. The string is used as it literally is. You should always keep this in mind when programming in PHP.

Integer types

Integers can be brokn down a little more into another 3 types:

  • Integers - Normal numbers
  • Floats - Numbers with decimal places
  • Boolean - 1 (true) or 0 (false)

I wantws to break these down into their basics, but I'm actually not going to bother, because at their basics. Integers are numbers that don't have any decimal places. Floats are numbers with with decimal places. Booleans are either 1 which is TRUE, or 0 which is FALSE, we'll go into the boolean stuff a little more when we do evaluation for control structures. I'm not really going to go into floats, for the most part they are the same as Integers.

Lets have a look at some code with numbers, but things might start to become a little confusing soon, so try stay with me.

Variables in PHP can be easily cast from one type to another. Casting means converted. So a integer can be converted to a string and a string to a integer on the fly. You need to be careful about this though, because you can end up getting yourself into a bind.

Here's a very basic integer assignment:

<?php
        $int = 5;
        echo $int;
?>

You'll notice that we output a integer exactly the same way as we would a string. We can concatenate it onto a string, the same way we would a string too:

<?php
        $int = 5;
        echo "I had ".$int." glasses of water today";
?>

You can perform math on integers too. The basic break down is simple:

  • "+" is for addition
  • "-" is for subtraction
  • "*" is for multiplication
  • "/" is for division
  • "%" is for modulus (getting the remainder of a division)

Here's some code to simply explain it:

<?php
        echo "5 + 3 = ".(5 + 3)."<br>\n";
        echo "8 - 6 = ".(8 - 6)."<br>\n";
        echo "4 * 5 = ".(4 * 5)."<br>\n";
        echo "12 / 3 = ".(12 / 3)."<br>\n";
        echo "16 % 5 = ".(16 % 5)."<br>\n";
?>

This will output the following to your browser:

5 + 3 = 8
8 - 6 = 2
4 * 5 = 20
12 / 3 = 4
16 % 5 = 1

The division operator will return a float if the two numbers don't divide completely. (I actually didn't know this at time of writing, seems you learn something new everyday).
<?php
        echo "13 / 3 = ".(13 / 3)."<br>\n";
?>

Will output:
13 / 3 = 4.33333333333

Integers are for the most part pretty basic, if you can do an equation in real life, you can do it in PHP, there are lots of functions that deal with operations on Integers past basic math. I'm not going to go into that, there is plenty of documentation on that if you wish to go into it on the PHP.net website.

Containers

Arrays make up the bulk of what we would call containers. One could class objects and even strings into containers, but we'll be focusing on Arrays.

An array is a list of variables in its simplest form. There are functions to add, remove and access the array. Since arrays are also stored in variables, you can have an array full of more arrays. It can at times get a little confusing, but arrays are extremely useful, so you should take the time to understand them correctly.

Lets have a look at a simple deceleration of an array:

<?php
        $myNameArray = array('Bobby', 'Brown');
        echo "Name: {$myNameArray[0]}<br>\n";
        echo "Name: {$myNameArray[1]}<br>\n";
 
?>

First we create a variable, $myNameArray, which we assign an array to. We do this by using the array command. When an array is created this way, the first element in the array, gets assigned the id of 0 and then any new elements added on afterwards are simply increments there of. In order to access the elements, we need to use the id it is stored by. That id is put in between square brackets ([]) at the end of the variable. So as you can see, we can access the two elements by $myNameArray[0] and $myNameArray[1].

We could achieve the same result by simply assigning the strings to the respective elements, like so:

        $myNameArray[0] = 'Bobby';
        $myNameArray[1] = 'Brown';
 
        echo "Name: {$myNameArray[0]}<br>\n";
        echo "Name: {$myNameArray[1]}<br>\n";

You can declare your own id's too if you want to and they can be be strings or integers. You do so, with the following format:

        $variable = array(id => value);

So your code would look something like this:
<?php
        $myNameArray = array('name' => 'Bobby', 'surname' => 'Brown');
        echo "Name: {$myNameArray['name']}<br>\n";
        echo "Surname: {$myNameArray['surname']}<br>\n";
 
        $myNameArray = array(5 => 'Bobby', 8 => 'Brown');
        echo "Name: {$myNameArray[5]}<br>\n";
        echo "Surname: {$myNameArray[8]}<br>\n";
?>

As I said earlier, you can create an array that contains other arrays. This is called a multi-dimensional array. They too can be very useful, but you should make sure you keep track of what is going on, as they get tricky very quickly.

Here we will create a new name array. The array will contain a list of 2 elements arrays, which in turn hold a name and surname:

<?php
        $myNameArray = array(
                array('name' => 'Bobby', 'surname' => 'Brown'),
                array('name' => 'Sam', 'surname' => 'Jenkins'),
                array('name' => 'John', 'surname' => 'Snith')
        );
 
        echo "Name: {$myNameArray[0]['name']}<br>\n";
        echo "Surname: {$myNameArray[0]['surname']}<p>\n";
 
        echo "Name: {$myNameArray[1]['name']}<br>\n";
        echo "Surname: {$myNameArray[1]['surname']}<p>\n";
 
        echo "Name: {$myNameArray[2]['name']}<br>\n";
        echo "Surname: {$myNameArray[2]['surname']}<p>\n";
 
?>

As you can see, I create 3 arrays in a parent array. I don't set the id's for those arrays, but I do set the id's for the internal ones (I know, it's confusing, but try stay with me). So I access the parent array by it's number id in the first square brackets and then the child id by the second bracket.

Have a play around with it so you can better understand how they work.

I had planned to go onto Control structures, Loops and Evaluation in this entry, but it seems that the geshi filter I used to create the pretty blocks of code can only handle so many at a time, before it has a hissy fit and doesn't render any of the code at all. It's a pity, because I've been working on this post for over two a weeks now (I've been very busy) and it was looking to be a rather large one, full of content. I hope to have the next installment up soon(tm).

Syn