Freeola Internet Get Dotted Domains Blog Guides Chat
Menu

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

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

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 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:




My HTML web page


My web page



This is my web page!



It has a .htm file extension!






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



// 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.
?>



My web page


My web page



This is my web page!



Hello world!

"; ?>


It has a .php file extension.






In the above, you should see how to use the PHP tags 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):


// This is a single lined PHP comment.
echo "

This isn’t a PHP comment, and would appear on your web page.

";

# This is also a single lined PHP comment.
echo "

This also isn’t a PHP comment, and would appear on your web page.

";

/*
This is a multi-lined PHP comment, that
can span as many lines as
you feel the need to.

*/
?>


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:


$var1 = "Hello";
$Var2 = "world";
$_var3 = "!";
$var4 = 25;
$VAR4 = 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:


$1var = "Hello";
$Va-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:


echo "

$var1 $Var2$_var3

";
?>


… 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.


$names = array("Anna", "Anthony", "Becky", "Billy");
?>


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:


$names = array("manager"=>"Anna", "Anthony", "Becky", "teamleader"=>"Billy");
?>


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:


$names = array( "manager"=>"Anna", "Anthony", "Becky", "manager"=>"Billy");
?>


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.


$names[] = "Anna";
$names[] = "Anthony";
$names[] = "Becky";
$names[] = "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:


$names["manager"] = "Anna";
$names[] = "Anthony";
$names[] = "Becky";
$names["teamleader"] = "Billy";
?>


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


// 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[3], 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[“teamleader”], for example, the code:


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).




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 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.


echo '

Hello world!

';
echo "

Hello world!

";
?>


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).


$var1 = 'Hello';
$var2 = 'world!';
echo '

$var1 $var2

';
echo "

$var1 $var2

";
?>


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:


// New echo for each.
echo "

Hello";
echo FIRSTNAME;
echo " "; // Space.
echo LASTNAME;
echo ", how are you?

";

// in and out of echo.
echo "

Hello".FIRSTNAME." ".LASTNAME.", how are you?

";
?>


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:


echo "

\"myclass\">Hello world!

";
?>


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:


$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:


$var1 .= "Hello";
$var1 .= " "; // add a space
$var1 .= "world";
$var1 .= "!";
?>


... 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:


// Set some variables.
$var1 = 25;
$var2 = 50;
$var3 = 75;
$var4 = 100;

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

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


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


echo $results[0]."
";// Output the 1st result, followed by the
element.

echo $results[1]."
";// Output the 2nd result, followed by the
element.

echo $results[2]."
";// Output the 3rd result, followed by the
element.

echo $results[3]."
";// Output the 4th result, followed by the
element.

echo $results[4]."
";// Output the 5th result, followed by the
element.

// … and so on for each result.
?>


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 ($results as $temp) {
echo "Result: $temp
";
}


$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 }:


if ($employee == "billy") {
// Code to execute if the above condition is met.
echo "

Hello Billy!

";
}
?>


… or …


if ($employee != "billy") {
// Code to execute if the above condition is met.
echo "

Hello employee, who isn’t Billy!

";
}
?>


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


$Billy = 42;
$Anna = 32;
if ($Billy > $Anna) {
echo "Billy is older than Anna";
}
?>


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:


if ($employee == "billy") {
// Code to execute if the above condition is met.
echo "

Hello Billy!

";
} else {
// Code to execute if the above condition is not met.
echo "

Hello employee!

";
}
?>


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.


if ($employee == "billy") {
echo "

Hello Billy!

";
} else if ($employee == "Anna") {
echo "

Hello Anna!

";
} else if ($employee == "Becky") {
echo "

Hello Becky!

";
} else {
echo "

Hello employee!

";
}
?>


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 .

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.


// Call my function, passing in some variables.
$var1 = "Hello";
$var2 = "world! ";
myfirstfunction($var1,$var2);

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


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.


function myfirstfunction() {
// function code goes in here.
echo "

Hello world!.

";
}
?>


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:


function myfirstfunction($catchvar1,$catchvar2) {
// function code goes in here.
echo "

$catchvar1 $catchvar2

";
}
?>


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:
cjh
Regular
"It goes so quickly"
Posts: 4,083
A quick introduction to PHP, a server-side scripting language

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 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:




My HTML web page


My web page



This is my web page!



It has a .htm file extension!






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



// 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.
?>



My web page


My web page



This is my web page!



Hello world!

"; ?>


It has a .php file extension.






In the above, you should see how to use the PHP tags 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):


// This is a single lined PHP comment.
echo "

This isn’t a PHP comment, and would appear on your web page.

";

# This is also a single lined PHP comment.
echo "

This also isn’t a PHP comment, and would appear on your web page.

";

/*
This is a multi-lined PHP comment, that
can span as many lines as
you feel the need to.

*/
?>


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:


$var1 = "Hello";
$Var2 = "world";
$_var3 = "!";
$var4 = 25;
$VAR4 = 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:


$1var = "Hello";
$Va-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:


echo "

$var1 $Var2$_var3

";
?>


… 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.


$names = array("Anna", "Anthony", "Becky", "Billy");
?>


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:


$names = array("manager"=>"Anna", "Anthony", "Becky", "teamleader"=>"Billy");
?>


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:


$names = array( "manager"=>"Anna", "Anthony", "Becky", "manager"=>"Billy");
?>


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.


$names[] = "Anna";
$names[] = "Anthony";
$names[] = "Becky";
$names[] = "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:


$names["manager"] = "Anna";
$names[] = "Anthony";
$names[] = "Becky";
$names["teamleader"] = "Billy";
?>


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


// 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[3], 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[“teamleader”], for example, the code:


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).




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 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.


echo '

Hello world!

';
echo "

Hello world!

";
?>


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).


$var1 = 'Hello';
$var2 = 'world!';
echo '

$var1 $var2

';
echo "

$var1 $var2

";
?>


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:


// New echo for each.
echo "

Hello";
echo FIRSTNAME;
echo " "; // Space.
echo LASTNAME;
echo ", how are you?

";

// in and out of echo.
echo "

Hello".FIRSTNAME." ".LASTNAME.", how are you?

";
?>


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:


echo "

\"myclass\">Hello world!

";
?>


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:


$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:


$var1 .= "Hello";
$var1 .= " "; // add a space
$var1 .= "world";
$var1 .= "!";
?>


... 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:


// Set some variables.
$var1 = 25;
$var2 = 50;
$var3 = 75;
$var4 = 100;

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

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


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


echo $results[0]."
";// Output the 1st result, followed by the
element.

echo $results[1]."
";// Output the 2nd result, followed by the
element.

echo $results[2]."
";// Output the 3rd result, followed by the
element.

echo $results[3]."
";// Output the 4th result, followed by the
element.

echo $results[4]."
";// Output the 5th result, followed by the
element.

// … and so on for each result.
?>


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 ($results as $temp) {
echo "Result: $temp
";
}


$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 }:


if ($employee == "billy") {
// Code to execute if the above condition is met.
echo "

Hello Billy!

";
}
?>


… or …


if ($employee != "billy") {
// Code to execute if the above condition is met.
echo "

Hello employee, who isn’t Billy!

";
}
?>


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


$Billy = 42;
$Anna = 32;
if ($Billy > $Anna) {
echo "Billy is older than Anna";
}
?>


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:


if ($employee == "billy") {
// Code to execute if the above condition is met.
echo "

Hello Billy!

";
} else {
// Code to execute if the above condition is not met.
echo "

Hello employee!

";
}
?>


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.


if ($employee == "billy") {
echo "

Hello Billy!

";
} else if ($employee == "Anna") {
echo "

Hello Anna!

";
} else if ($employee == "Becky") {
echo "

Hello Becky!

";
} else {
echo "

Hello employee!

";
}
?>


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 .

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.


// Call my function, passing in some variables.
$var1 = "Hello";
$var2 = "world! ";
myfirstfunction($var1,$var2);

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


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.


function myfirstfunction() {
// function code goes in here.
echo "

Hello world!.

";
}
?>


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:


function myfirstfunction($catchvar1,$catchvar2) {
// function code goes in here.
echo "

$catchvar1 $catchvar2

";
}
?>


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 is a UK internet service provider offering the best value and extensive free services. Please compare our domain name registration prices or check out our UK high speed internet access. If you are in business please see examples of our free hosting at Freeola.com/customer-sites.

Safe and Secure Payment