GetDotted Domains

Viewing Thread:
"A quick introduction to PHP, a server-side scripting language"

The "Freeola Customer Forum" forum, which includes Retro Game Reviews, has been archived and is now read-only. You cannot post here or create a new thread or review on this forum.

Sun 18/02/07 at 23:44
Regular
"It goes so quickly"
Posts: 4,083
[B][U]A quick introduction to PHP, a server-side scripting language[/U][/B]

What is PHP?

PHP is a server-side scripting language that is available to you as a Freeola customer, free of charge. PHP allows you to make a dynamic and truly interactive web site that can be embedded in to your current HTML web pages. Using PHP opens up huge possibilities for your web site that isn’t available to you within HTML. You can work with text files, the MySQL service that Freeola offers, create images on the fly, to name but a few.

The Freeola forums are a good example of a dynamic and interactive web site using PHP, which let visitors add to the site via a user account.

This article is a basic introduction to PHP (a recursive acronym for PHP: Hypertext Preprocessor), and won’t cover every possible task that can be accomplished with it. It is assumed that you (the reader) have a basic grasp of HTML, so lets just dive right in.

Using PHP in a web page!

You don’t need any special software to write a PHP script. It can be written in a standard text editor in the same way HTML can be. The final file can also be uploaded to your Freeola web space just as an HTML page is. The only difference is that a PHP file needs to have a .php file extension, rather than a .htm or .html extension. This is so the Freeola web servers know which files to send to its PHP parser, so that your code can be run (or “executed”). You can also use a PHP file as your index file, simply by calling it index.php.

To include PHP within your web page, you need to use the opening <?php tag, which tells the PHP parser to expect PHP code, and to run it. Once you’ve finished your piece of PHP code, you need to add the closing ?> tag, so the parser knows to stop, and let the rest of the page load as normal.

A standard HTML web page, with a .htm file extension, may look like this:


<html>
<head>
<title>My HTML web page</title>
</head>
<body>
<h1>My web page</h1>

<p>This is my web page!</p>

<p>It has a <strong>.htm</strong> file extension!</p>
</body>
</html>


Whereas a web page with PHP, with a .php file extension, may look like this:


[B]<?php[I]
// This is where your PHP code can go.
// We've finished with PHP for the moment, so we'll use the closing PHP tag to get back to HTML.
[/I]?>[/B]
<html>
<head>
<title>My web page</title>
</head>
<body>
<h1>My web page</h1>

<p>This is my web page!</p>

[B]<?php echo "<p>Hello world!</p>"; ?>[/B]

<p>It has a <strong>.php</strong> file extension.</p>
</body>
</html>


In the above, you should see how to use the PHP tags <?php and ?> to jump in and out. You can place whatever PHP code you like between the two tags, and the PHP parser will pick it up and run it.

If you clicked on the web page with PHP example, you’ll see the text Hello world!, but without the surrounding PHP code around it. If you view the source, you’ll also only see HTML code. This is because the PHP code is executed on the web server, and so will not be seen by the person looking at your web pages. You can tell PHP to output text to your web page, which is talked about in the “Output to your web page” section further down the page.

Making a comment!

When putting together your scripts, it can be helpful to make little notes, or “comments” to yourself, so that when you come back to the code at a later date, you’ve left yourself a little reminder as to what you were trying to achieve. You probably won’t need them for smaller scripts, but they can be very helpful for larger PHP script, as well as for other people who may have access to your code (such as a work colleague).

A PHP comment can be added in three ways, two as a single line, using a hash (#) or double forward-slashes (//) at the front, and one that can span more than one line, which is enclosed between an opening /* and a closing */ (which is the same as a CSS comment), for example (echo outputs to your web page, and is mentioned later):


<?php
[B]//[/B] [I]This is a single lined PHP comment.[/I]
echo "<p>This isn�t a PHP comment, and would appear on your web page.</p>";

[B]#[/B] [I]This is also a single lined PHP comment.[/I]
echo "<p>This also isn�t a PHP comment, and would appear on your web page.</p>";

[B]/*[/B]
[I]This is a multi-lined PHP comment, that
can span as many lines as
you feel the need to.[/I]
[B]*/[/B]
?>


When the PHP parser comes across a comment, is simply ignores it. There is no other general rules that need to be followed, but be sure to use meaningful comments, otherwise they will be useless too you when you need them.

Data storage!

Like many computer languages, PHP allows you to create data stores, that can hold a value, or values, which you can then reference throughout your script, either to simply output to the web browser, or manipulate accordingly. This can be done using a variable, an array or a constant.

Variables!

A variable allows you to hold a single value that can be made up of letters, numbers or characters symbols, such as a plus sign (+), back-slash (\), or exclamation point (!). It can also hold other types of data, but we’ll leave that for the time being.

A variable needs to be “created” and given a name and a value to hold, which can be done using the dollar sign ($), followed by the name you want to assign, followed by an equals sign (=), and then the value you want the variable to hold, surrounded by quotation marks where necessary (for text values, but not for numbers) and finished of with a semi-colon (;).

Variable names can only be made up of letters (a-z or A-Z), numbers (0-9), or the underscore character (_). A variable cannot begin with a number, nor can it have a space or other characters in it (including a dash, as to PHP, this is the mathematical “minus” symbol). Variables are also case-sensitive.

For example:


<?php
[B]$var1[/B] = "Hello";
$Var2 = [B]"world"[/B];
$_var3 = "!"[B];[/B]
$[B]var4[/B] = 25;
$[B]VAR4[/B] = 35;
?>


… are all valid because they start with a letter or an underscore, and have used difference case (even though the name may look the same to you or I), whereas:


<?php
$[B]1[/B]var = "Hello";
$Va[B]-[/B]r2 = "world";
$_v ar3 = "!";
?>


… are all invalid because they start with a number, or contain a symbol, and a space respectively, which are all prohibited.

If you were to attempt the above, you would be greeted with a standard PHP error code.

To reference a variable later on in your script, you simply need to use the dollar sign ($) with the name, for example, if you wanted the above three variable values to be seen on your web page, you would use the following code:


<?php
echo "<p>$var1 $Var2$_var3</p>";
?>


… would output “Hello world!”. Don’t worry, we will come to echo in a little bit.

Array’s!

An array allows you to group variable-like entries together under a single reference. For example, if you had a list of names you had planned to store in variables, an array would be a better way to do so.

An array can be looked on as a filing cabinet of values, as each value is given a unique index, allowing you to grab whichever value you were looking for. The index is by default, simply counted, although you can assign a named index for each if you wish.

To create an array, PHP gives you two options. The built-in array function, or the array identifier. Whichever you use is down to personal preference, as one is not really any different from the other in terms of performance, and both finish with the same result, an array.

Array function

The array function is built-in to PHP, and allows you to create many entries at once. You can either let PHP build the index for you, define it yourself, or a little of both.

The code below will create an array called $names, which contains four entries, the values of which are “Anna”, “Anthony”, “Becky” and “Billy” respectively.


<?php
$names = array([B]"Anna", "Anthony", "Becky", "Billy"[/B]);
?>


As mentioned, you can create your own index, using text to reference each entry. To do this, you’ll need to set each text reference when creating each entry, using => before setting each value, for example:


<?php
$names = array([B]"manager"=>[I]"Anna"[/I][/B], "Anthony", "Becky", [B]"teamleader"=>[I]"Billy"[/I][/B]);
?>


You can’t use the same text reference for more than one entry, for example, the following wouldn’t work, because the text reference “manager” has been used more than once, and the first would be overwritten by the last:


<?php
$names = array([B] "manager"=>[I]"Anna"[/I][/B], "Anthony", "Becky", [B] "manager"=>[I]"Billy"[/I][/B]);
?>


Array identifier

An array identifier is really the method used to reference an array entry (see below), but makes use of the assign symbol (equals, or =) in the same way a variable does. The code below will create an array that is exactly the same as the one created using the above code.


<?php
$names[B][][/B] = "Anna";
$names[B][][/B] = "Anthony";
$names[B][][/B] = "Becky";
$names[B][][/B] = "Billy";
?>


As with the array function, you can set your own text index if required, simply by placing your desired index value between the square brackets, for example:


<?php
$names[B]["manager"][/B] = "Anna";
$names[] = "Anthony";
$names[] = "Becky";
$names[B]["teamleader"][/B] = "Billy";
?>


You can combine the above if you wish, using the array first, then using the array identifier after, for example:


<?php
// Create the array, and add four entries.
$names = array("manager"=>"Anna", "Anthony", "Becky", "teamleader"=>"Billy");

// Add more entries to the array created earlier.
$names["driver"] = "Charlene";
$names[] = "Debbie";
$names["supervisor"] = "Fred";
$names[] = "Molly";
$names[] = "Ned";
$names[] = "Sally";
$names["janitor"] = "Zack";
?>


Referencing an array entry!

Whichever method you pick, the auto indexing done by PHP starts from zero (0), and not one (1), so to reference these individually later on, you’ll need to use the array name, followed by square brackets [] which enclose the number of the entry you want, for example, to reference the value of “Billy”, you would need to use $names[[B]3[/B]], because even though we see it as the fourth entry, PHP sees it as the third, as the index started from zero 0. You can also reference an entry via its text reference such as $names[[B]�teamleader�[/B]], for example, the code:


<?php
echo $names[3];
echo $names["teamleader"];
?>


… would reference and output the same value of Billy our fourth employee and current team leader.

Constants!

A constant is similar to a variable, in that it can hold a single value, and follows the same rules when it comes to naming them. The difference is that you are unable to change the value you assign to a constant once you have done so.

To create a constant, you must use the built-in PHP function define, which requires you to enclose your desired name and value within parenthesis (rounded brackets).

<?php define("FIRSTNAME","Fred"); ?>
<?php define("LASTNAME","Price"); ?>

When referencing a constant, you don’t use the dollar sign ($), like you would for a variable.

Output to your web page!

PHP includes the echo language construct (as seen above), which allows you to output variables, array entries, constants, or just plain text to your web page, without having to jump in and out of PHP using the opening <?php and closing ?> tags. When outputting just a variable, array entry or constant, you don’t need to use quotation marks. However, when mixing these with plain text, quotes would be needed.

Single quotes and double quotes!

If you look at the code sample below, you’ll noticed that the first echo statement uses single quotes, while the second uses double quotes.


<?php
echo '<p>Hello world!</p>';
echo "<p>Hello world!</p>";
?>


In this instance, there is no difference (as seen here), because no variables or special characters are referenced. The difference becomes apparent when we make use of a couple of variables to recreate the above (seen here).


<?php
$var1 = 'Hello';
$var2 = 'world!';
echo '<p>$var1 $var2</p>';
echo "<p>$var1 $var2</p>";
?>


Single quotes don’t parse variables or special characters, whereas double quotes do. Because of this difference, you may just want to stick with double quotes, just to keep things simple.

To output a constant, you need to fall out of the echo statement. You can do this either by finishing and starting a new statement, or using a full stop after a quote, adding the constant name, then another full stop, and another quote. Both methods are shown below:


<?php
[S]// New echo for each.[/S]
echo "<p>Hello";
echo FIRSTNAME;
echo " "; // [S]Space.[/S]
echo LASTNAME;
echo ", how are you?</p>";

[S]// in and out of echo.[/S]
echo "<p>Hello".FIRSTNAME." ".LASTNAME.", how are you?</p>";
?>


If you want to output quotation marks within an echo statement (such as when using an HTML attribute), you’ll need to “escape” it with a back-slash (\), so the PHP parser knows that a particular quote isn’t the end of the statement. For example:


<?php
echo "<p class=[B]\[/B]"myclass[B]\[/B]">Hello world!</p>";
?>


Working with data storage!

Once set, a variable or an array entry can be changed (a constant cannot, once it’s set, that’s it). PHP includes a few features that allow you to manipulate them to your liking. The below examples work with array entries also, but for simplicity, I’ll just refer to them as variables.

Changing a value

To change a value of a variable, you can simply redefine it, overwriting the previously set variable value, for example:


<?php
$var1 = "Hello";
$var1 = "world";
$var1 = "!";
?>


... would cause the final value of $var1 to be the exclamation point (!), because the previous values have been over written.

Concatenating to a value

Concatenating means to “link up” or “add to the end of”, which PHP allows you to do with variables. This is done by added a full stop before the equals sign in the code above, for example:


<?php
$var1 [B].=[/B] "Hello";
$var1 [B].=[/B] " "; [S]// add a space[/S]
$var1 [B].=[/B] "world";
$var1 [B].=[/B] "!";
?>


... would cause the final value of $var1 to be Hello world!, because each additional value was added to the end of the same variable, rather than the previous values being over written.

Maths

You can perform maths calculations on variables in PHP, which are pretty self explanatory, so here are some quick examples:


<?php
[S]// Set some variables.[/S]
$var1 = 25;
$var2 = 50;
$var3 = 75;
$var4 = 100;

[S]// Play with them.[/S]
$results[] = $var1 + $var2; [S]// plus - equals 75.[/S]
$results[] = $var4 - $var3; [S]// minus - Equals 25.[/S]
$results[] = $var2 * $var3; [S]// multiply - equals 3750.[/S]
$results[] = $var4 / $var1; [S]// divided by - equals 4.[/S]
$results[] = $var4 + $var2 * $var3 / $var1; [S]// a mix � equals 450.[/S]

$results[] = $var1[B]++[/B]; [S]// plus 1 - equals 26.[/S]
$results[] = $var2[B]�[/B]; [S]// minus 1 - Equals 49.[/S]
$results[] = $var1 [B]+= 5[/B]; [S]// plus 5 - equals 30.[/S]
$results[] = $var2 [B]-= 20[/B]; [S]// minus 20 - equals 30.[/S]
$results[] = $var3 [B]*= 50[/B]; [S]// multiply by 50 � equals 3750.[/S]
$results[] = $var4 [B]/= 4[/B]; [S]// divided by 4 - 25.[/S]
?>


The above would create an array of calculations called $results, which you could reference as mentioned previously, for example:


<?php
echo $results[0]."<br>";[S]// Output the 1[S]st[/S] result, followed by the <br> element.[/S]
echo $results[1]."<br>";[S]// Output the 2[S]nd[/S] result, followed by the <br> element.[/S]
echo $results[2]."<br>";[S]// Output the 3[S]rd[/S] result, followed by the <br> element.[/S]
echo $results[3]."<br>";[S]// Output the 4[S]th[/S] result, followed by the <br> element.[/S]
echo $results[4]."<br>";[S]// Output the 5[S]th[/S] result, followed by the <br> element.[/S]
[S]// � and so on for each result.[/S]
?>


Wouldn’t it be easier if you could just loop through the above? Well you can.

Loop though your array

If you want to loop through an array, you can use the foreach function, that’ll basically take each entry from your array, and perform whatever action you want it to. For example, if we wanted to print out our maths from above, rather than writing out each entry, we can loop through each and perform the echo output statement, a shown below:


foreach ([B]$results[/B] as $temp) {
echo "<strong>Result:</strong> $temp<br>";
}


$temp is a temporary variable that we need to create, as this will hold the current array entry that is being worked on. You can name this variable anything you want (as with other variables), but $temp is an obvious choice in this case, and is unlikely to be used elsewhere by you in your scripts.

Conditions!

Like many other computer languages, PHP allows you to execute segments of code based on particular conditions. These conditions are generally a “How does this value compare to that value”, which include the comparisons of:

== (two equal signs) – do the two values match?
!= – do the two values not match?
> – is the first value larger than the second?
>= – is the first value larger than or the same as the second?
< – is the first value smaller than the second?
<= – is the first value smaller than or the same as the second?

One thing to note is that the first comparison example is TWO (2) equal signs, not one. If you only use one, PHP will think you’re just assigning a value to a variable, which isn’t what you want to do here.

You can make a comparison on one (or more) values from a variable, array, etc and compare it a pre-set text value, or another variable, array, etc.

For example, if we were to create a variable called $employee which contained the name of the person who was logged in to the staff network, we could used an “equals to” or “not equal to” check, as shown below.

if

The if is the bare bones of the comparison code, and the comparison condition(s) go in between the standard parenthesis. It can check for whether a comparison is matched, and allows a block of code to be executed if it is, as shown below for “equals to” or “not equal to” respectively. The block of code must go between a pair of curly brackets, one opening bracket {, and one closing }:


<?php
[B]if ([U]$employee[/U] == "billy") {[/B]
[S]// Code to execute if the above condition is met.[/S]
echo "<p>Hello Billy!</p>";
[B]}[/B]
?>


… or …


<?php
[B]if ([U]$employee[/U] != "billy") {[/B]
[S]// Code to execute if the above condition is met.[/S]
echo "<p>Hello employee, who isn�t Billy!</p>";
[B]}[/B]
?>


The other four comparisons are generally suited to numeric values, for example:


<?php
$Billy = 42;
$Anna = 32;
[B]if ($Billy > $Anna) {[/B]
echo "Billy is older than Anna";
[B]}[/B]
?>


if, else

When using the else clause along-side an if statement, we are able to execute some PHP code if the comparison isn’t met, as well as if it is, allowing us to provide an alternative if need be, for example, if Billy isn’t the member of staff logged in, we’ll great whomever is politely:


<?php
[B]if ([U]$employee[/U] == "billy") {[/B]
[S]// Code to execute if the above condition is met.[/S]
echo "<p>Hello Billy!</p>";
[B]} else {[/B]
[S]// Code to execute if the above condition is not met.[/S]
echo "<p>Hello employee!</p>";
[B]}[/B]
?>


if, else if, else

Adding the else if clauses allows us to make multiple checks, as well as provide an alternative, allowing use to greet Billy, Anna, Becky, or an unknown member of staff.


<?php
[B]if ([U]$employee[/U] == "billy") {[/B]
echo "<p>Hello Billy!</p>";
[B]} else if ([U]$employee[/U] == "Anna") {[/B]
echo "<p>Hello Anna!</p>";
[B]} else if ([U]$employee[/U] == "Becky") {[/B]
echo "<p>Hello Becky!</p>";
[B]} else {[/B]
echo "<p>Hello employee!</p>";
[B]}[/B]
?>


You can only use one if and else clause per block, but can use as many else if clauses as you feel are required.

Functions!

As already seen, PHP has many built -in functions that you can take advantage of. These are all listed on the PHP web site, under the function reference. There are too many to be able to go through, though hopefully sometime down the line an article will appear that makes the built-in functions it easier to digest. You are of course welcome to ask at any time on the Freeola web forum for any information.

Custom Functions!

A custom function is one that you can put together yourself. It enables you to section off chunks of code that you can then call upon, as and when you need it, as many times as you require.

To call your function is done in the same way as calling a built-in function, by stating the name of the function, followed by parenthesis (curly brackets), followed by a semi-colon (;). For example, if your custom function was named myfirstfunction, you would need to call it using the code <?php myfirstfunction(); ?>.

Within the parenthesis, you can pass values or variables to your function, separating each with a comma (,). These values can then be used by your custom function.


<?php
[S]// Call my function, passing in some variables.[/S]
$var1 = "Hello";
$var2 = "world! ";
myfirstfunction([B]$var1,$var2[/B]);

[S]// Call my function, passing in some text.[/S]
myfirstfunction([B]"Hello","world!"[/B]);
??


To create your function, you need to first use the function keyword, followed by the name you want to give your function (and what will be used to call it later on), followed by parenthesis, and an opening curly bracket ({) and a closing curly bracket (}). In between the curly brackets is where you will house your custom code, which can be pretty much whatever PHP you want it to be.


<?php
function [B]myfirstfunction[/B]() {
// function code goes in here.
echo "<p>Hello world!.</p>";
}
?>


As mentioned above, you can pass values to you functions, to use within. To ensure your function knows this, you’ll need to “catch” each one that you pass as a variable of it’s own. This is done within the parenthesis, and each required variable is divided with a comma (,), for example, to catch our previous calls to our custom function that include two values, we would need to create two catch variables, which can be done as follow:


<?php
function myfirstfunction([B]$catchvar1,$catchvar2[/B]) {
// function code goes in here.
echo "<p>$catchvar1 $catchvar2</p>";
}
?>


Still quite a way to go!

This little article aimed to give you a small introduction to the PHP scripting language, but doesn’t come close to teaching you everything you need to know. Hopefully, you can use this to give you a bump in the right direction though.

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

As always, any comments, questions, and especially corrections are welcome.
There have been no replies to this thread yet.
Sun 18/02/07 at 23:44
Regular
"It goes so quickly"
Posts: 4,083
[B][U]A quick introduction to PHP, a server-side scripting language[/U][/B]

What is PHP?

PHP is a server-side scripting language that is available to you as a Freeola customer, free of charge. PHP allows you to make a dynamic and truly interactive web site that can be embedded in to your current HTML web pages. Using PHP opens up huge possibilities for your web site that isn’t available to you within HTML. You can work with text files, the MySQL service that Freeola offers, create images on the fly, to name but a few.

The Freeola forums are a good example of a dynamic and interactive web site using PHP, which let visitors add to the site via a user account.

This article is a basic introduction to PHP (a recursive acronym for PHP: Hypertext Preprocessor), and won’t cover every possible task that can be accomplished with it. It is assumed that you (the reader) have a basic grasp of HTML, so lets just dive right in.

Using PHP in a web page!

You don’t need any special software to write a PHP script. It can be written in a standard text editor in the same way HTML can be. The final file can also be uploaded to your Freeola web space just as an HTML page is. The only difference is that a PHP file needs to have a .php file extension, rather than a .htm or .html extension. This is so the Freeola web servers know which files to send to its PHP parser, so that your code can be run (or “executed”). You can also use a PHP file as your index file, simply by calling it index.php.

To include PHP within your web page, you need to use the opening <?php tag, which tells the PHP parser to expect PHP code, and to run it. Once you’ve finished your piece of PHP code, you need to add the closing ?> tag, so the parser knows to stop, and let the rest of the page load as normal.

A standard HTML web page, with a .htm file extension, may look like this:


<html>
<head>
<title>My HTML web page</title>
</head>
<body>
<h1>My web page</h1>

<p>This is my web page!</p>

<p>It has a <strong>.htm</strong> file extension!</p>
</body>
</html>


Whereas a web page with PHP, with a .php file extension, may look like this:


[B]<?php[I]
// This is where your PHP code can go.
// We've finished with PHP for the moment, so we'll use the closing PHP tag to get back to HTML.
[/I]?>[/B]
<html>
<head>
<title>My web page</title>
</head>
<body>
<h1>My web page</h1>

<p>This is my web page!</p>

[B]<?php echo "<p>Hello world!</p>"; ?>[/B]

<p>It has a <strong>.php</strong> file extension.</p>
</body>
</html>


In the above, you should see how to use the PHP tags <?php and ?> to jump in and out. You can place whatever PHP code you like between the two tags, and the PHP parser will pick it up and run it.

If you clicked on the web page with PHP example, you’ll see the text Hello world!, but without the surrounding PHP code around it. If you view the source, you’ll also only see HTML code. This is because the PHP code is executed on the web server, and so will not be seen by the person looking at your web pages. You can tell PHP to output text to your web page, which is talked about in the “Output to your web page” section further down the page.

Making a comment!

When putting together your scripts, it can be helpful to make little notes, or “comments” to yourself, so that when you come back to the code at a later date, you’ve left yourself a little reminder as to what you were trying to achieve. You probably won’t need them for smaller scripts, but they can be very helpful for larger PHP script, as well as for other people who may have access to your code (such as a work colleague).

A PHP comment can be added in three ways, two as a single line, using a hash (#) or double forward-slashes (//) at the front, and one that can span more than one line, which is enclosed between an opening /* and a closing */ (which is the same as a CSS comment), for example (echo outputs to your web page, and is mentioned later):


<?php
[B]//[/B] [I]This is a single lined PHP comment.[/I]
echo "<p>This isn�t a PHP comment, and would appear on your web page.</p>";

[B]#[/B] [I]This is also a single lined PHP comment.[/I]
echo "<p>This also isn�t a PHP comment, and would appear on your web page.</p>";

[B]/*[/B]
[I]This is a multi-lined PHP comment, that
can span as many lines as
you feel the need to.[/I]
[B]*/[/B]
?>


When the PHP parser comes across a comment, is simply ignores it. There is no other general rules that need to be followed, but be sure to use meaningful comments, otherwise they will be useless too you when you need them.

Data storage!

Like many computer languages, PHP allows you to create data stores, that can hold a value, or values, which you can then reference throughout your script, either to simply output to the web browser, or manipulate accordingly. This can be done using a variable, an array or a constant.

Variables!

A variable allows you to hold a single value that can be made up of letters, numbers or characters symbols, such as a plus sign (+), back-slash (\), or exclamation point (!). It can also hold other types of data, but we’ll leave that for the time being.

A variable needs to be “created” and given a name and a value to hold, which can be done using the dollar sign ($), followed by the name you want to assign, followed by an equals sign (=), and then the value you want the variable to hold, surrounded by quotation marks where necessary (for text values, but not for numbers) and finished of with a semi-colon (;).

Variable names can only be made up of letters (a-z or A-Z), numbers (0-9), or the underscore character (_). A variable cannot begin with a number, nor can it have a space or other characters in it (including a dash, as to PHP, this is the mathematical “minus” symbol). Variables are also case-sensitive.

For example:


<?php
[B]$var1[/B] = "Hello";
$Var2 = [B]"world"[/B];
$_var3 = "!"[B];[/B]
$[B]var4[/B] = 25;
$[B]VAR4[/B] = 35;
?>


… are all valid because they start with a letter or an underscore, and have used difference case (even though the name may look the same to you or I), whereas:


<?php
$[B]1[/B]var = "Hello";
$Va[B]-[/B]r2 = "world";
$_v ar3 = "!";
?>


… are all invalid because they start with a number, or contain a symbol, and a space respectively, which are all prohibited.

If you were to attempt the above, you would be greeted with a standard PHP error code.

To reference a variable later on in your script, you simply need to use the dollar sign ($) with the name, for example, if you wanted the above three variable values to be seen on your web page, you would use the following code:


<?php
echo "<p>$var1 $Var2$_var3</p>";
?>


… would output “Hello world!”. Don’t worry, we will come to echo in a little bit.

Array’s!

An array allows you to group variable-like entries together under a single reference. For example, if you had a list of names you had planned to store in variables, an array would be a better way to do so.

An array can be looked on as a filing cabinet of values, as each value is given a unique index, allowing you to grab whichever value you were looking for. The index is by default, simply counted, although you can assign a named index for each if you wish.

To create an array, PHP gives you two options. The built-in array function, or the array identifier. Whichever you use is down to personal preference, as one is not really any different from the other in terms of performance, and both finish with the same result, an array.

Array function

The array function is built-in to PHP, and allows you to create many entries at once. You can either let PHP build the index for you, define it yourself, or a little of both.

The code below will create an array called $names, which contains four entries, the values of which are “Anna”, “Anthony”, “Becky” and “Billy” respectively.


<?php
$names = array([B]"Anna", "Anthony", "Becky", "Billy"[/B]);
?>


As mentioned, you can create your own index, using text to reference each entry. To do this, you’ll need to set each text reference when creating each entry, using => before setting each value, for example:


<?php
$names = array([B]"manager"=>[I]"Anna"[/I][/B], "Anthony", "Becky", [B]"teamleader"=>[I]"Billy"[/I][/B]);
?>


You can’t use the same text reference for more than one entry, for example, the following wouldn’t work, because the text reference “manager” has been used more than once, and the first would be overwritten by the last:


<?php
$names = array([B] "manager"=>[I]"Anna"[/I][/B], "Anthony", "Becky", [B] "manager"=>[I]"Billy"[/I][/B]);
?>


Array identifier

An array identifier is really the method used to reference an array entry (see below), but makes use of the assign symbol (equals, or =) in the same way a variable does. The code below will create an array that is exactly the same as the one created using the above code.


<?php
$names[B][][/B] = "Anna";
$names[B][][/B] = "Anthony";
$names[B][][/B] = "Becky";
$names[B][][/B] = "Billy";
?>


As with the array function, you can set your own text index if required, simply by placing your desired index value between the square brackets, for example:


<?php
$names[B]["manager"][/B] = "Anna";
$names[] = "Anthony";
$names[] = "Becky";
$names[B]["teamleader"][/B] = "Billy";
?>


You can combine the above if you wish, using the array first, then using the array identifier after, for example:


<?php
// Create the array, and add four entries.
$names = array("manager"=>"Anna", "Anthony", "Becky", "teamleader"=>"Billy");

// Add more entries to the array created earlier.
$names["driver"] = "Charlene";
$names[] = "Debbie";
$names["supervisor"] = "Fred";
$names[] = "Molly";
$names[] = "Ned";
$names[] = "Sally";
$names["janitor"] = "Zack";
?>


Referencing an array entry!

Whichever method you pick, the auto indexing done by PHP starts from zero (0), and not one (1), so to reference these individually later on, you’ll need to use the array name, followed by square brackets [] which enclose the number of the entry you want, for example, to reference the value of “Billy”, you would need to use $names[[B]3[/B]], because even though we see it as the fourth entry, PHP sees it as the third, as the index started from zero 0. You can also reference an entry via its text reference such as $names[[B]�teamleader�[/B]], for example, the code:


<?php
echo $names[3];
echo $names["teamleader"];
?>


… would reference and output the same value of Billy our fourth employee and current team leader.

Constants!

A constant is similar to a variable, in that it can hold a single value, and follows the same rules when it comes to naming them. The difference is that you are unable to change the value you assign to a constant once you have done so.

To create a constant, you must use the built-in PHP function define, which requires you to enclose your desired name and value within parenthesis (rounded brackets).

<?php define("FIRSTNAME","Fred"); ?>
<?php define("LASTNAME","Price"); ?>

When referencing a constant, you don’t use the dollar sign ($), like you would for a variable.

Output to your web page!

PHP includes the echo language construct (as seen above), which allows you to output variables, array entries, constants, or just plain text to your web page, without having to jump in and out of PHP using the opening <?php and closing ?> tags. When outputting just a variable, array entry or constant, you don’t need to use quotation marks. However, when mixing these with plain text, quotes would be needed.

Single quotes and double quotes!

If you look at the code sample below, you’ll noticed that the first echo statement uses single quotes, while the second uses double quotes.


<?php
echo '<p>Hello world!</p>';
echo "<p>Hello world!</p>";
?>


In this instance, there is no difference (as seen here), because no variables or special characters are referenced. The difference becomes apparent when we make use of a couple of variables to recreate the above (seen here).


<?php
$var1 = 'Hello';
$var2 = 'world!';
echo '<p>$var1 $var2</p>';
echo "<p>$var1 $var2</p>";
?>


Single quotes don’t parse variables or special characters, whereas double quotes do. Because of this difference, you may just want to stick with double quotes, just to keep things simple.

To output a constant, you need to fall out of the echo statement. You can do this either by finishing and starting a new statement, or using a full stop after a quote, adding the constant name, then another full stop, and another quote. Both methods are shown below:


<?php
[S]// New echo for each.[/S]
echo "<p>Hello";
echo FIRSTNAME;
echo " "; // [S]Space.[/S]
echo LASTNAME;
echo ", how are you?</p>";

[S]// in and out of echo.[/S]
echo "<p>Hello".FIRSTNAME." ".LASTNAME.", how are you?</p>";
?>


If you want to output quotation marks within an echo statement (such as when using an HTML attribute), you’ll need to “escape” it with a back-slash (\), so the PHP parser knows that a particular quote isn’t the end of the statement. For example:


<?php
echo "<p class=[B]\[/B]"myclass[B]\[/B]">Hello world!</p>";
?>


Working with data storage!

Once set, a variable or an array entry can be changed (a constant cannot, once it’s set, that’s it). PHP includes a few features that allow you to manipulate them to your liking. The below examples work with array entries also, but for simplicity, I’ll just refer to them as variables.

Changing a value

To change a value of a variable, you can simply redefine it, overwriting the previously set variable value, for example:


<?php
$var1 = "Hello";
$var1 = "world";
$var1 = "!";
?>


... would cause the final value of $var1 to be the exclamation point (!), because the previous values have been over written.

Concatenating to a value

Concatenating means to “link up” or “add to the end of”, which PHP allows you to do with variables. This is done by added a full stop before the equals sign in the code above, for example:


<?php
$var1 [B].=[/B] "Hello";
$var1 [B].=[/B] " "; [S]// add a space[/S]
$var1 [B].=[/B] "world";
$var1 [B].=[/B] "!";
?>


... would cause the final value of $var1 to be Hello world!, because each additional value was added to the end of the same variable, rather than the previous values being over written.

Maths

You can perform maths calculations on variables in PHP, which are pretty self explanatory, so here are some quick examples:


<?php
[S]// Set some variables.[/S]
$var1 = 25;
$var2 = 50;
$var3 = 75;
$var4 = 100;

[S]// Play with them.[/S]
$results[] = $var1 + $var2; [S]// plus - equals 75.[/S]
$results[] = $var4 - $var3; [S]// minus - Equals 25.[/S]
$results[] = $var2 * $var3; [S]// multiply - equals 3750.[/S]
$results[] = $var4 / $var1; [S]// divided by - equals 4.[/S]
$results[] = $var4 + $var2 * $var3 / $var1; [S]// a mix � equals 450.[/S]

$results[] = $var1[B]++[/B]; [S]// plus 1 - equals 26.[/S]
$results[] = $var2[B]�[/B]; [S]// minus 1 - Equals 49.[/S]
$results[] = $var1 [B]+= 5[/B]; [S]// plus 5 - equals 30.[/S]
$results[] = $var2 [B]-= 20[/B]; [S]// minus 20 - equals 30.[/S]
$results[] = $var3 [B]*= 50[/B]; [S]// multiply by 50 � equals 3750.[/S]
$results[] = $var4 [B]/= 4[/B]; [S]// divided by 4 - 25.[/S]
?>


The above would create an array of calculations called $results, which you could reference as mentioned previously, for example:


<?php
echo $results[0]."<br>";[S]// Output the 1[S]st[/S] result, followed by the <br> element.[/S]
echo $results[1]."<br>";[S]// Output the 2[S]nd[/S] result, followed by the <br> element.[/S]
echo $results[2]."<br>";[S]// Output the 3[S]rd[/S] result, followed by the <br> element.[/S]
echo $results[3]."<br>";[S]// Output the 4[S]th[/S] result, followed by the <br> element.[/S]
echo $results[4]."<br>";[S]// Output the 5[S]th[/S] result, followed by the <br> element.[/S]
[S]// � and so on for each result.[/S]
?>


Wouldn’t it be easier if you could just loop through the above? Well you can.

Loop though your array

If you want to loop through an array, you can use the foreach function, that’ll basically take each entry from your array, and perform whatever action you want it to. For example, if we wanted to print out our maths from above, rather than writing out each entry, we can loop through each and perform the echo output statement, a shown below:


foreach ([B]$results[/B] as $temp) {
echo "<strong>Result:</strong> $temp<br>";
}


$temp is a temporary variable that we need to create, as this will hold the current array entry that is being worked on. You can name this variable anything you want (as with other variables), but $temp is an obvious choice in this case, and is unlikely to be used elsewhere by you in your scripts.

Conditions!

Like many other computer languages, PHP allows you to execute segments of code based on particular conditions. These conditions are generally a “How does this value compare to that value”, which include the comparisons of:

== (two equal signs) – do the two values match?
!= – do the two values not match?
> – is the first value larger than the second?
>= – is the first value larger than or the same as the second?
< – is the first value smaller than the second?
<= – is the first value smaller than or the same as the second?

One thing to note is that the first comparison example is TWO (2) equal signs, not one. If you only use one, PHP will think you’re just assigning a value to a variable, which isn’t what you want to do here.

You can make a comparison on one (or more) values from a variable, array, etc and compare it a pre-set text value, or another variable, array, etc.

For example, if we were to create a variable called $employee which contained the name of the person who was logged in to the staff network, we could used an “equals to” or “not equal to” check, as shown below.

if

The if is the bare bones of the comparison code, and the comparison condition(s) go in between the standard parenthesis. It can check for whether a comparison is matched, and allows a block of code to be executed if it is, as shown below for “equals to” or “not equal to” respectively. The block of code must go between a pair of curly brackets, one opening bracket {, and one closing }:


<?php
[B]if ([U]$employee[/U] == "billy") {[/B]
[S]// Code to execute if the above condition is met.[/S]
echo "<p>Hello Billy!</p>";
[B]}[/B]
?>


… or …


<?php
[B]if ([U]$employee[/U] != "billy") {[/B]
[S]// Code to execute if the above condition is met.[/S]
echo "<p>Hello employee, who isn�t Billy!</p>";
[B]}[/B]
?>


The other four comparisons are generally suited to numeric values, for example:


<?php
$Billy = 42;
$Anna = 32;
[B]if ($Billy > $Anna) {[/B]
echo "Billy is older than Anna";
[B]}[/B]
?>


if, else

When using the else clause along-side an if statement, we are able to execute some PHP code if the comparison isn’t met, as well as if it is, allowing us to provide an alternative if need be, for example, if Billy isn’t the member of staff logged in, we’ll great whomever is politely:


<?php
[B]if ([U]$employee[/U] == "billy") {[/B]
[S]// Code to execute if the above condition is met.[/S]
echo "<p>Hello Billy!</p>";
[B]} else {[/B]
[S]// Code to execute if the above condition is not met.[/S]
echo "<p>Hello employee!</p>";
[B]}[/B]
?>


if, else if, else

Adding the else if clauses allows us to make multiple checks, as well as provide an alternative, allowing use to greet Billy, Anna, Becky, or an unknown member of staff.


<?php
[B]if ([U]$employee[/U] == "billy") {[/B]
echo "<p>Hello Billy!</p>";
[B]} else if ([U]$employee[/U] == "Anna") {[/B]
echo "<p>Hello Anna!</p>";
[B]} else if ([U]$employee[/U] == "Becky") {[/B]
echo "<p>Hello Becky!</p>";
[B]} else {[/B]
echo "<p>Hello employee!</p>";
[B]}[/B]
?>


You can only use one if and else clause per block, but can use as many else if clauses as you feel are required.

Functions!

As already seen, PHP has many built -in functions that you can take advantage of. These are all listed on the PHP web site, under the function reference. There are too many to be able to go through, though hopefully sometime down the line an article will appear that makes the built-in functions it easier to digest. You are of course welcome to ask at any time on the Freeola web forum for any information.

Custom Functions!

A custom function is one that you can put together yourself. It enables you to section off chunks of code that you can then call upon, as and when you need it, as many times as you require.

To call your function is done in the same way as calling a built-in function, by stating the name of the function, followed by parenthesis (curly brackets), followed by a semi-colon (;). For example, if your custom function was named myfirstfunction, you would need to call it using the code <?php myfirstfunction(); ?>.

Within the parenthesis, you can pass values or variables to your function, separating each with a comma (,). These values can then be used by your custom function.


<?php
[S]// Call my function, passing in some variables.[/S]
$var1 = "Hello";
$var2 = "world! ";
myfirstfunction([B]$var1,$var2[/B]);

[S]// Call my function, passing in some text.[/S]
myfirstfunction([B]"Hello","world!"[/B]);
??


To create your function, you need to first use the function keyword, followed by the name you want to give your function (and what will be used to call it later on), followed by parenthesis, and an opening curly bracket ({) and a closing curly bracket (}). In between the curly brackets is where you will house your custom code, which can be pretty much whatever PHP you want it to be.


<?php
function [B]myfirstfunction[/B]() {
// function code goes in here.
echo "<p>Hello world!.</p>";
}
?>


As mentioned above, you can pass values to you functions, to use within. To ensure your function knows this, you’ll need to “catch” each one that you pass as a variable of it’s own. This is done within the parenthesis, and each required variable is divided with a comma (,), for example, to catch our previous calls to our custom function that include two values, we would need to create two catch variables, which can be done as follow:


<?php
function myfirstfunction([B]$catchvar1,$catchvar2[/B]) {
// function code goes in here.
echo "<p>$catchvar1 $catchvar2</p>";
}
?>


Still quite a way to go!

This little article aimed to give you a small introduction to the PHP scripting language, but doesn’t come close to teaching you everything you need to know. Hopefully, you can use this to give you a bump in the right direction though.

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

As always, any comments, questions, and especially corrections are welcome.

Freeola & GetDotted are rated 5 Stars

Check out some of our customer reviews below:

Just a quick note to say thanks for a very good service ... in fact excellent service..
I am very happy with your customer service and speed and quality of my broadband connection .. keep up the good work . and a good new year to all of you at freeola.
Matthew Bradley
LOVE it....
You have made it so easy to build & host a website!!!
Gemma

View More Reviews

Need some help? Give us a call on 01376 55 60 60

Go to Support Centre
Feedback Close Feedback

It appears you are using an old browser, as such, some parts of the Freeola and Getdotted site will not work as intended. Using the latest version of your browser, or another browser such as Google Chrome, Mozilla Firefox, or Opera will provide a better, safer browsing experience for you.