PHP Tutorials

Tutorial 3 - Variables and String Handling

Some new terms will be introduced to you in this tutorial; hopefully by the end you'll understand what these new terms mean. So far you will have only learnt how PHP works in basic terms. This tutorial will help you to start understanding how real PHP scripts and applications work/function. This is because many actual PHP scripts will use variables. Variables are used to store values (e.g. text, numbers etc). These can then be used in a variety of ways, as they keep their value once they've been set. Hence you could refer to the same variable multiple times in the same script (if needed). Once set, variables can be combined, or altered in various ways. This is explained in the "String/Variable Handling" section later. The concept of variables is explained more below.


Quick Reference:
Variables
String/Variable Handling

Variables Top

As mentioned above, variables are used to store values. Once a variable is set in a PHP script, they can be used over and over again as much as is needed. Variables don't just store text or basic numbers. There are actually eight different data types (i.e. types of values) in PHP. These are:

A variable is started using a dollar sign: $. The name of the variable then follows. For example: $MyName. The following code shows how to set a value to a variable:


<?php

$MyName
= 'Tristan Perry';
// The variable $MyName contains the value Tristan Perry
// The value is stored by using the equals sign.
// The variable is then ended by a semi-colon (;).
// Notice how quotation marks are put around the value. The use of quotation marks here follow the same rules as in http://www.phpmission.com/Tutorial2-BasicPHP.php#echo
// Looking at the above list, can you figure out what data type the value is?
// Yep, you (hopefully!) chosen right: it's a string.
?>

As explained above, quotation marks are put around the value. If the value contains an apostrophe, the apostrophe needs to be escaped, as explained in Tutorial 2's echo command section. Lets look at some more examples of how to set variables:


<?php

$MyAge
= 17;
// Notice how quotation marks aren't needed here. This is because the data stored is an integer.

$AverageExamMark = 76.3;
// Again, double quotation marks aren't needed. This is because the data is a number (looking at the above list, you can see it's a 'double').

$My_Age = 17;
// Variable names can include underscores (_). They cannot, however, include hyphens (-). So you won't be able to do $My-Name etc.

$AverageExamMark = '76.3%';
// Although 76.3 is a number, the percentage symbol means that this value now becomes a string. Hence quotation marks around this are needed. Trying to leave out the quotation marks (and thus having $AverageExamMark = 76.3%) would result in an error being shown.

?>

It's also important to note that, once a variable is set, you can use it in many ways. For example, you can refer to a variable when performing an echo command:
<?php

$BestFootballTeam
= 'Cardiff City FC!';

echo
$BestFootballTeam;
// This would output Cardiff City FC
// This is useful because, if you have a particular string that you use a lot, you can simply put the string into a variable, instead of having to type it out time after time.
// Notice how the $BestFootballTeam variable didn't need quotation marks around it. This is because, although the value of $BestFootballTeam contains a string, you don't need to use quotation marks when actually dealing with a variable.
?>

String/Variable Handling Top

Once a string value is set as a variable, it can be handled/altered in various ones. One way of working with strings can be by joining – or concatenating – them. Concatenating strings/variables can be done by using the full stop (.) operator. For example if you had one variable $MyFirstName = 'Tristan'; and another $MySurname = 'Perry'; , you could use the concatenation operator to join these, thus creating a new variable: $MyFullName = $MyFirstName . $MySurname;. You could also use the concatenation operator in an echo command. This idea is illustrated below:
<?php

$MyFirstName
= 'Tristan';
$MySurname = 'Perry';

echo
$MyFirstName . $MySurname;
// This would literally output TristanPerry
// Notice that there's no space between my names. This can be changed by either adding a space into one of the variables, or you could use the concatenation operator to include a space...

echo $MyFirstName . ' '. $MySurname;
// This would output Tristan Perry
// Notice that the space has quotation marks around it. This is because (oddly) PHP counts a space as a character. This means, therefore, that a space on its own is actually counted as a string (hence it requires quotation marks around it).

// However, if I wanted, I could equally have set "$MyFirstName . $MySurname" as a variable first, and then output it:

$MyName = $MyFirstName . ' ' . $MySurname;
echo
$MyName;
// This would output Tristan Perry

?>

String Functions

In PHP, there are various commands – known as 'functions' – that will perform certain actions. There are over 50 functions (scroll down to "Table Of Contents" to see them) just for string manipulation alone. The PHP website is very useful – it contains documentation of each function. Hence if you are a bit confused by something I mean below, you could consult the PHP website (or contact me and I'll help you out). Some of the more common string-related functions are outlined below.

The 'echo' function. This is a technicality, although the echo command (detailed in the previous tutorial) is technically a function. As explained earlier, 'echo' is used to output a string.

The 'echo' function. This is a technicality, although the echo command (detailed in the previous tutorial) is technically a function. As explained earlier, 'echo' is used to output a string.

strlen() The strlen() function is used to calculate the length of a string. A commercial example of this is in e-commerce. A website that sells goods may want to check that a credit card number given is legitimate. A basic check that they could do is to check the length of the number given. If it was anything other than 16, then they could identify right away that the credit card number given is false.


<?php
$MyName
= 'Tristan Perry';

echo
strlen($MyName);
// This would output the number 13. The space in the $MyName variable is also counted in the strlen() function.

// You could also set the output of strlen() (i.e. 13) to a variable if you wanted. You can also do this with any function:

$LengthOfMyName = strlen($MyName);
// $LengthOfMyName now contains the integer value 13

echo $LengthOfMyName;
// This would output 13
?>

strpos() This function finds the first occurrence of a particular string, within a string or variable.


<?php

$TheAlphabet
= 'abcdefghijklmnopqrstuvwxyz';

echo
strpos($TheAlphabet,'f');
// This would output 5
// In other words, find where the string 'f' appears in the variable $TheAlphabet
// After scanning $TheAlphabet, PHP finds that 'f' appears as the 6th character in the string.
// Huh? Then why does it output 5, and not 6?
// This is because PHP is (again!) odd. Quite often you'll find that it starts counting from 0, and not 1. Hence 'a' would be the 0th character, 'b' would be the 1st, and z would be the 25th character.

$Welcome = 'Hello, my name is Tristan Perry. I\'m here to teach you PHP.';
$NamePos = strpos($Welcome,'name');
echo
$NamePos;
// This would output 10

?>

strtoupper() This function takes a string, and changes any lowercase letters into uppercase letters.


<?php
$MyName
= 'Tristan Perry';

$UppercaseName = strtoupper($MyName);

echo
$UppercaseName;
// This would output TRISTAN PERRY

?>

strtolower() This function takes a string, and changes any uppercase letters into lowercase letters. You use this function in exactly the same way as strtoupper() (it just has a different name).

substr() This function returns part of a particular string/variable.


<?php

$TheAlphabet
= 'abcdefghijklmnopqrstuvwxyz';

$F_to_P = substr($TheAlphabet,5,10);
// The variable $F_to_P would now contain fghijklmnop
// The first value given in the function substr() is the variable to analyse. The next value is where the function starts returning from (e.g. the 5th character – F – in this case), and the last value is how long the function keeps going (in this case, for 10 characters).
// Notice again how the 5th character is taken to be F – this is because PHP starts counting from 0, hence the 5th character (in PHP) would be the same as the 6th character (to us Humans!)

$F_onwards = substr($TheAlphabet,5);
echo
$F_onwards;
// This would output fghijklmnopqrstuvwxyz
// If you don't give a third value (i.e. the length to continue on for – 10), then substr() will start from the character specified (in this case the 5th character), and it'll then continue on until the end of the string.

// And now for a more complicated example. Did you know you could use functions within functions?
// Therefore, instead of getting confused by trying to figure out the position of "f" in the string, we could combine substr() and strpos()...

$TheAlphabet = 'abcdefghijklmnopqrstuvwxyz';

$F_to_P = substr($TheAlphabet,strpos($TheAlphabet,'f'),10);
echo
$F_to_P;
// This would output fghijklmnop
// This shows the flexibility with PHP. You can use functions inside functions. This will make them more complicated to read (if reviewing your code), although it'll save time (otherwise you'd have to set the output of strpos() to a variable, and then reference that variable in the function, etc).

// Complicated enough for you? You could take this up another notch, too, if you wanted...!
$TheAlphabet = 'abcdefghijklmnopqrstuvwxyz';

$F_to_P = substr($TheAlphabet,strpos($TheAlphabet,'f'),strpos($TheAlphabet,'p')-strpos($TheAlphabet,'f'));
echo
$F_to_P;
// This would output fghijklmnop
// This probably looks confusing as heck, although it's only the third value (in the function) that has changed. It's gone from simply "10" to:
// strpos($TheAlphabet,'p')-strpos($TheAlphabet,'f')
// What this does is find the position of p (16 to Humans, 15 to PHP), and then take this away from the position of f (6 to Humans, 5 to PHP). Hence this bit of code actually does: 15 – 5 (= 10).
// Hence the substr() function, after processing the strpos() values would be: substr($TheAlphabet,5,10)

?>

A fairly lengthy tutorial perhaps, although hopefully this will have helped you to understand more about PHP and how it's used in a more real environment.