Substr () PHP Function

The Substr () PHP Function is used to return part of a string. It is written as substr (string, start, optional length);.The string is whatever string you want to return a portion of. The start is how many characters in to skip before starting. Setting this to 3 would skip the first three and start returning at the forth character. Setting this to a negative number will start counting backwards from the end of the string.
Length is an optional parameter. If you set this to a positive number, it will return that number of characters. If you set this to a negative number it will count that many numbers from the end of the string and return whatever is left in the middle.
See how this works :

<?php
// this will return bcdefghijk
echo substr(’abcdefghijk’, 1);
echo “<br>”;

// this will return defghijk
echo substr(’abcdefghijk’, 3);
echo “<br>”;

// this will return abc
echo substr(’abcdefghijk’, 0, 3);
echo “<br>”;

// this will return ijk
echo substr(’abcdefghijk’, -3);
echo “<br>”;

// this will return bcdefghij
echo substr(’abcdefghijk’, 1, -1);
echo “<br>”;

// this will return cdefgh
echo substr(’abcdefghijk’, 2, -3);
echo “<br>”;
?>

Difference between isset empty is null

I have come across code that checks for empty or null values, or if a variable is set. Many of these checks fail as the wrong function is being used to assert the correct value. While it is important to be checking values, it is equally important to understand the difference between the different methods of checking and testing values for empty, null, or if they are set.

Most common is the incorrect use of isset() and empty(). Many times these are seen to be used interchangeably, where the reality is, that the two are complete opposites. Look at some code.

<?php

var_dump( !isset( $var ) );

var_dump( empty( $var ) );

?>

The above snippet tests for not isset and empty for a variable which has not been set. The results both return true.

bool(true)
bool(true)

The correct method to check if a variable is set or not, is with the isset() function, or, if checking for an empty variable, then use empty(). These functions are provided for good reason, as seen in this code below.

<?php

error_reporting(E_ALL);
if( ! isset(
$var ) )

{
echo ‘Variable is not set<br />’;
}
if( empty(
$var ) )

{
echo ‘Variable is empty<br />’;
}
if(
$var )

{
echo ‘Variable is set<br />’;
}
?>

The above snippet produces the following..

Variable is not set

Variable is empty

Notice: Undefined variable: var in /test.php on line 15

This shows why the use of if($var) type syntax is shunned by many programmers, as PHP throws an E_NOTICE error when it finds an uninitialized variable. The checks for isset and empty declare the variable is not set, and that it is empty? Which is it? The Empty function would have us believe the variable is set, but the value is empty, but this is not the case, the variable is clearly undefined, and the third test which gives and error supports this. Confused?

To make matters just a little more complex, the empty function will also return true, if the variable has a value of zero. Lets take it for a drive.

<?php

/*** turn on error reporting ***/
error_reporting(E_ALL);

/*** set variable to zero ***/
$var = 0;
if( isset(
$var ) )
{
echo
‘Variable is set<br />’;
}

if( empty( $var ) )
{
echo
‘Variable is empty<br />’;
}

if( $var )
{
echo
‘Variable is set<br />’;
}
?>

Running this test, provides some more clues to the behavior mentioned earlier. The response is:

Variable is set

Variable is empty

At the top of the script, the variable is clearly set to zero, and a check with isset asserts this. However, the next check with the empty function shows the variable to be empty, even though a value for it has been set. Then the final check with if( $var ) does not show the text for the same reason empty shows the variable to be empty.

To get a better understanding of this seemingly odd behavior lets make a quick test chart can be produced to check for values and the values each returns based on the function that is checking each of the values. The code for producing such a table is provided below, but, here is one we prepared earlier. The error message is produced because the isset() function is trying to check a variable that has not been initialized, as seen earlier in this article.

Notice: Undefined variable: var in /test.php on line 10

TEST Not Set NULL Zero FALSE Numeric Value Empty String
Comparison Table
isset() bool(false) bool(false) bool(true) bool(true) bool(true) bool(true)
empty() bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)
is_null() bool(true) bool(true) bool(false) bool(false) bool(false) bool(false)
== bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)
=== bool(false) bool(false) bool(false) bool(true) bool(false) bool(false)

The Comparison Table Code

<table style=”border: solid 1px black; width:100%;”>

<tr style=”text-align:left;”><th>TEST</th><th>Not Set</th><th>NULL</th><th>Zero</th><th>FALSE</th><th>Numeric Value</th><th>Empty String</th></tr>
<tfoot><tr><td colspan=”6″>Comparison Table</td></tr></tfoot>
<tbody>
<?php
/*** turn on error reporting ***/
error_reporting( E_ALL );

/*** an array of test values ***/
$values = array( $var, null, 0, false, 100, );
echo
‘<tr>’;
echo
‘<td>isset()</td>’;
foreach(
$values as $val )
{
echo
‘<td>’;
var_dump( isset( $val ) );
echo
‘</td>’;
}
echo
‘</tr>’;

echo ‘<tr>’;
echo
‘<td>empty()</td>’;
foreach(
$values as $val )
{
echo
‘<td>’;
var_dump( empty( $val ) );
echo
‘</td>’;
}
echo
‘</tr>’;

echo ‘<tr>’;
echo
‘<td>is_null()</td>’;
foreach(
$values as $val )
{
echo
‘<td>’;
var_dump( is_null( $val ) );
echo
‘</td>’;
}
echo
‘</tr>’;

echo ‘<tr>’;
echo
‘<td>==</td>’;
foreach(
$values as $val )
{
echo
‘<td>’;
var_dump( $val == false );
echo
‘</td>’;
}
echo
‘</tr>’;

echo ‘<tr>’;
echo
‘<td>===</td>’;
foreach(
$values as $val )
{
echo
‘<td>’;
var_dump( $val === false );
echo
‘</td>’;
}
echo
‘</tr>’;
?>
</tbody>
</table>

PHP Type Casting

Contents

  1. Types
  2. Casting
  3. Check for Type

The PHP is often referred to as “loosely typed” or “dynaically typed”. What this means is that variable types are detirmined by context. Lets jump straight into some code to see it in action.


<?php

/*** create a number as a string ***/
$var = “6″;

/*** display the variable type and value ***/
var_dump($var);

echo ‘<br />’;

/*** increment the variable ***/
$var++;

/*** display the variable type and value ***/
var_dump($var);

?>


The above code will produce the following output:

string(1) “6″

int(7)

We began with a string value of 6 and then incremented the variable using the ++ operand. PHP has noted the context of the operation and internally converted the type to INT.

Types

PHP supports many different types, these include

  • int
  • string
  • binary
  • unicode
  • array
  • boolean
  • bool (same as boolean)
  • object
  • float
  • double (same as float)
  • real (same as float)

Casting

The ability of PHP to be able to dynamically type variables makes for quick and lean code. But for those times where we absolutely need the variable to be of a particular type, the variable must be cast. This is done in much the same way as in C.

Cast To String


<?php

/*** create an int ***/
$num = 6;

/*** dump the type ***/
var_dump($num);

echo ‘<br />’;

/*** cast to string ***/
$num = (string) $num;

/*** dump again ***/
var_dump($num);
?>


The above script shows us the variable begins as an integer and then is cast to a string.

int(6)

string(1) “6″

Cast To Int

Just as PHP allows casting to string, the same applies when casting to an integer


<?php

/*** create an string ***/
$string = “26″;

/*** dump the type ***/
var_dump($string);

echo ‘<br />’;

/*** cast to int ***/
$string = (int) $string;

/*** dump again ***/
var_dump($string);

?>


The above script tells that the string is created and then converted to an int.

string(2) “26″

int(26)

Try changing the value of the value of the sting to a non-numerical value such as “this is a string”. The result, after casting, would then be int(0).

Cast To Binary

Cast To Unicode

Cast To Boolean


<?php

/*** create an int ***/
$num = 1;

/*** dump the type ***/
var_dump($num);

echo ‘<br />’;

/*** cast to bool ***/
$bool = (bool) $num;

/*** dump again ***/
var_dump($bool);

?>


The above script will output the following:

int(1)

bool(true)

The script ouputs bool(true) because “1″ is considered to be a true boolean value. Other values that evaluate to boolean true are:

  • -1
  • “string”
  • 1.6e5

So, basically, any non zero value will evalute to boolean true. Values that evaluate to boolean false are:

  • 0
  • “0″
  • “”
  • FALSE
  • array()
  • NULL

Cast To Object

This is quite groovy. Casting an array to an object allows the use of the array as an object, using the corresponding keys and values.

<?php

/*** create an array ***/
$array = array(‘animal’=>‘koala’, ‘name’=>‘bruce’, ‘type’=>‘marsupial’);

/*** cast to an object ***/
$object = (object)$array;

/*** use the array as an object ***/
echo $object->name;

?>


If any other type, such as a sting or integer is cast to an object, PHP creates an instance of stdClass and the value is contained within the class member scalar as shown here:


<?php

/*** create an array ***/
$string = ‘this is a string’;

/*** cast to an object ***/
$object = (object)$string;

/*** output the value ***/
echo $object->scalar;

?>


The above string outputs “this is a string” as the string value has been assigned internally by PHP to the special class member “scalar”.

Cast To Float

Floats are also known as double or real values and casting is generally considered to be a bad idea with PHP as the precision needed with floats is not readily available as PHP has a finite amount of numbers. Better results can be had with the bc functions.

Check for Type

Up to this point we have dealt with converting or casting types. But there will be times when we need to check what type of variable a script is using. PHP comes with several ways to achieve this with the is_* functions and the charater type, or ctype_* functions.

Check String

In PHP most variables are strings to begin with, so this is rather straight forward.


<?php

/*** a simple string ***/
$string = ‘This is a string’;

/*** check if value is a string ***/
if(is_string($string))
{
echo
$string;
}

?>


Check INT

PHP has several ways of checking if the value of a variable is an integer, using the is_int() function is the preferred method. The is_interger() and is_long functions are both an alias of is_int().


<?php

/*** a simple int ***/
$int = 1234;

/*** check if value is a int ***/
if(is_int($int))
{
echo
$int;
}

?>


Of course, we could use the ctype_digit() function to check also.


<?php

/*** a simple int ***/
$int = 1234;

/*** check if value is a int ***/
if(ctype_digit($int))
{
echo
$int;
}

?>


Note:

While the function is_numeric() also checks the value of a string for numbers, it should not be used as it also returns try for floats and scientific notification.

Check Array

To check if a value is or type array, simply use is_array() as we have seen earlier with other types, you should have the swing of this by now..


<?php

/*** a simple array ***/
$array = array(‘animal’=>‘koala’, ‘name’=>‘bruce’, ‘type’=>‘marsupial’);

/*** check if value is an array ***/
if(is_array($array))
{
/*** cast array to object ***/
$obj = (object)$array;
/*** echo the name value ***/
echo $obj->name;
}

?>


The above code outputs “bruce”. As we saw in the Cast To Object section we can cast the array to an object. In this instance we have first checked that the value is indeed an array with the is_array() function.

Check Object

No surprises here as to what function is used to check if a variable is an object.. is_object().


<?php

/*** a simple object ***/
$obj = new stdClass;

/*** check if value is an object ***/
if(is_object($obj))
{
echo
‘Object found’;
}

?>


Check Float

To check if a variable is a float or double or real type, the is_float() function is used. It should be noted that all values from super globals such as $_GET or $_POST are strings and to check the values of these the is_numeric() function should be used. Here we show how to check for a floating point number.


<?php

/*** use pi as a floating point number ***/
$num = pi();

/*** check if value is an float ***/
if(is_float($num))
{
echo
$num;
}

?>


The above script checks the value of pi() and finds it has a value of 3.14159265359 and so, echoes the value.

Check Double

To check if a number is a double the is_double() function can be used. This function is an alias of is_float() and so the same procedure applies as seen in the section Check Float.

Check Real

To check if a number is a real type the is_real() function can be used. This function is an alias of is_float() and so the
same procedure applies as seen in the section Check Float.

Check Boolean

Checking a boolean value is quite simple, just as we have seen through-out this document the is_bool() function is used.


<?php

/*** create a boolean value ***/
$bool = is_int(0);

/*** check if value is boolean ***/
if(is_bool($bool))
{
var_dump($bool);
}

?>


In the above code we have checked if the number zero is an integer with the is_int() function. This returns boolean true on success so when checked with the is_bool() function we see that it is boolean and dumping the resulting variable shows bool(true).

Check Buffer

This bad boy checks if a variable is a native unicode or binary string. The is_buffer() function works the same as the other is_* functions


<?php

/*** create a unicode string ***/
$unicode = “û?Ìcöde”;

/*** check if value is unicode ***/
if(is_buffer($unicode))
{
echo
‘Unicode string’;
}

?>


Check Binary

To check if variable is a native binary, use the is_binary() function.


<?php
/*** no code for this function yet ***/

?>


Check Unicode

To check if a string is a unicode string, the is_unicode() function is used as below.


<?php

/*** create a unicode string ***/
$unicode = “û?Ìcöde”;

/*** check if value is unicode ***/
if(is_unicode($unicode))
{
echo
‘Unicode string’;
}

?>


Check NULL

To find if a variable value is NULL the is_null() function is used.


<?php

/*** create a null value ***/
$var = null;

/*** check if value is null ***/
if(is_null($var))
{
echo
‘Value is null’;
}
?>


Check Resource

A resource is a type returned by PHP from opened files and database connections. Using the is_resource() function a variable can be checked reliably.


<?php

/*** a database connection resource ***/
$conn = @mysql_connect(‘localhost’, ‘username’, ‘password’);

/*** check if connection is a valid resource ***/
if (is_resource($conn))
{
/*** show the resource type ***/
echo get_resource_type($conn);
}
else
{
/*** show an error on failure ***/
echo “Connection Failed: ”.mysql_error();
}

?>


Check Scalar

A scalar value is a variable value of type boolean, string, integer or float. All other types are considered non-scalar values. To check for a scalar value use the is_scalar() function.


<?php

/*** a string ***/
$string =“5.2″;

/*** check if value is scalar ***/
if (is_scalar($string))
{
echo
$string.‘ is scalar’;
}

?>


Simple email script in php

This chapter explains how to send email in php. We will upload advanced mailing script in php soon.

Download the script : Simple email script in PHP

Convert xml to html

This chapter explains how to display XML data as HTML. In the example below, we loop through an XML file (test.xml), and display each element as an HTML table row:

<script type=”text/javascript”>
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open(”GET”,”test.xml”,false);
xmlDoc.send(”");
xmlDoc=xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject(”Microsoft.XMLDOM”))
{
xmlDoc=new ActiveXObject(”Microsoft.XMLDOM”);
xmlDoc.async=false;
xmlDoc.load(”test.xml”);
}
document.write(”<table>”);
var x=xmlDoc.getElementsByTagName(”TEST”);
for (i=0;i<x.length;i++)
{
document.write(”<tr><td><b>”);
document.write(x[i].getElementsByTagName(”SNIPPET”)[0].childNodes[0].nodeValue);
document.write(”</b></td></tr><tr><td>”);
document.write(x[i].getElementsByTagName(”NAME”)[0].childNodes[0].nodeValue);
document.write(”</td></tr><tr><td>”);
document.write(x[i].getElementsByTagName(”EMAIL”)[0].childNodes[0].nodeValue);
document.write(”</td></tr><tr><td>”);
document.write(x[i].getElementsByTagName(”WEBSITE”)[0].childNodes[0].nodeValue);
document.write(”</td></tr><tr><td>”);
document.write(x[i].getElementsByTagName(”LICENSE”)[0].childNodes[0].nodeValue);
document.write(”</td></tr>”);
}
document.write(”</table>”);
</script>

* We check the browser, and load the XML using the correct parser
* We create an HTML table with <table>
* We use getElementsByTagName() to get all XML nodes
* For each TEST node, we display data from XML as table data.
* We end the table with </table>

Download the script : Convert-xml-to-html

PHP Tutorial - Part VI

Introduction
In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts useful.

Setting Up Your Form
Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in how to write your form but I will show you three of the main pieces of code you must know:
<input type=”text” name=”thebox” value=”Your Name”>
Will display a text input box with Your Name written in it as default. The value section of this code is optional. The information defined by name will be the name of this text box and should be unique.

<textarea name=”message”>Please write your message here.</textarea>
Will display a large scrolling text box with the text ‘Please write your message here.’ as default. Again, the name is defined and should be unique.

<input type=”submit” value=”Submit”>

This will create a submit button for your form. You can change what it says on the button by changing the button’s value. All the elements for your form must be enclosed in the <form> tags. They are used as follows:

<form action=”process.php” method=”post”>Form elements and formatting etc.</form>
The form’s action tells it what script to send its data to (in this case its process.php). This can also be a full URL (e.g. http://www.shashionline.in/scripts/process.php).
The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark e.g.
http://www.shashionline.in/process.php?name=shashi

It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser’s address bar.
Getting The Form Information

The next step is to get the data the form has submitted into your script so that you can do something with it. This is. There are basically two different methods of getting the data into
PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The
benefit of GET, though is that you can submit information to the script without a form, by simply
editing the URL.

This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:

yourpage.php?user=shashi could show shashi’s page and: yourpage.php?user=raj could show

raj’s page, using the same script. It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:

yourpage.php?user=shashi&referrer=gowansnet&area=6

These could all be accessed separately using the GET variables user, referrer and area.

To get a variable which has been sent to a script using the POST method you use the following code:
$variablename=$_POST['variable'];

which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variablename. Similarly, if you are using the GET method you should use the form:

$variablename=$_GET['variable'];

This should be done for each variable you wish to use from your form (or URL).

Creating The Form To Mail Script

To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user’s comments to you. Firstly, create this form for your HTML page:

<form action=”mail.php” method=”post”>

Your Name: <input type=”text” name=”name”><br>

E-mail: <input type=”text” name =”email”><br><br>

Comments<br>

<textarea name=”comments”></textarea><br><br>

<input type=”submit” value=”Submit”>

</form>
This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script:

<?

function
checkOK($field)

{

if (eregi(”\r”,$field) || eregi(”\n”,$field)){

die(”Invalid Input!”);

}

}

$name=$_POST['name'];

checkOK($name);

$email=$_POST['email'];

checkOK($email);

$comments=$_POST['comments'];

checkOK($comments);

$to=”info@shashionline.in”;

$message=”$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address was: $email”;

if(mail($to,”Comments From Your Site”,$message,”From: $email\n”)) {

echo “Thanks for your comments.”;

} else {

echo “There was a problem sending the mail. Please check that you filled in the form
correctly.”;

}

?>

Remember to replace info@shashionline.in with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your
comments form. The first part of that script may look a bit strange:

function checkOK($field)

{

if
(eregi(”\r”,$field) || eregi(”\n”,$field)){

die(”Invalid Input!”);

}

}
You don’t really need to worry about what this is doing, but basically, it stops spammers from using your form to send thier spam messages by checking special characters are not present
in the input which can be used to trick the computer into sending messages to other addresses. It is a fuction which checks for these characters, and if they are found, stops running the script.

The lines:

checkOK($name);etc. run this check on each input to ensure it is valid.

PHP Tutorial - Part V

Introduction
One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address.

The Mail Command
Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:
mail($to,$subject,$body,$headers);

In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.
The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mail but you can also include other headers like cc and bcc.

Sending An E-mail
Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:
$to = “info@shashionline.in”;
$subject = “PHP Is Great”;
$body = “PHP is one of the best scripting languages around”;
$headers = “From: webmaster@shashionline.in\n”;
mail($to,$subject,$body,$headers);
echo “Mail sent to $to”;


This code will acutally do two things. Firstly it will send a message to info@shashionline.in with the subject ‘PHP Is Great’ and the text:

PHP is one of the best scripting languages around and the e-mail will be from webmaster@shashionline.in. It will also output the text: Mail sent to info@shashionline.in to the browser.

Formatting E-mail
Something you may have noticed from the example is that the From line ended with \n. This is acutally a very important character when sending e-mail. It is the new line character and
tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

Mail Without Variables
The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could
also have been done on one line using text like this:

mail(”info@shashionline.in”,”PHP Is Great”,”PHP is one of the best scripting languages around”,”From:
webmaster@shashionline.in\n”);

Error Control
As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are
using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:
if(mail($to,$subject,$body,$headers))
{
echo “An e-mail was sent to $to with the subject: $subject”;
} else {
echo “There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid”;
}


This code is quite self explanitory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.

PHP Tutorial - Part IV

The WHILE Loop

The WHILE loop is one of the most useful commands in PHP. It is also quite easy to set up and use. A WHILE loop will, as the name suggests, execute a piece of code until a certain condition is met.
Repeating A Set Number Of Times

If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words “Hello World” 5 times you could use the following code:
$times = 5;
$x = 0;
while ($x
< $times) {
echo “Hello World”;
++$x;
}

Using $x

The variable counting the number of repeats ($x in the above example) can be used for much more than just counting. For example if you wanted to create a web page with all the numbers from 1 to 1000 on it, you could either type out every single one or you could use the following code:

$number = 1000;
$current
= 0;
while ($current < $number)
{
++$current;
echo
“$current<br>”;
}

There are a few things to notice about this code. Firstly, you will notice that I have placed the ++$current; before the echo statement. This is because, if I didn’t do this it would start printing numbers from 0, which is not what we want. The ++$current; line can be placed anywhere in your WHILE loop, it does not matter. It can, of course, add, subtract, multiply, divide or do anthing else to the number as well.

The other reason for this is that, if the ++$current; line was after the echo line, the loop would also stop when the number showed 999 because it would check $current which would equal 1000 (set in the last loop) and would stop, even though 1000 had not yet been printed.

Arrays

Arrays are common to many programing languages. They are special variables which can hold more than one value, each stored in its own numbered ’space’ in the array. Arrays are extremely useful, especially when using WHILE loops.

Setting Up An Array

Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 5 names in it:

$names[0] =
‘John’;
$names[1] = ‘Paul’;
$names[2] =
‘Steven’;
$names[3] = ‘George’;
$names[4] =
‘David’;

As you can see, the parts of an array are all numbered, starting from 0. To add a value to an array you must specify the location in the array by putting a number in [ ].

Reading From An Array

Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the number of the piece of data in the array. So if I wanted to print out the third name I could use the code:

style=”font-family: Arial;”>

echo “The third name is $names[2]“;

Which would output:

The third name is Steven

Using Arrays And Loops

One of the best uses of a loop is to output the information in an array. For instance if I wanted to print out the following list of names:

Name 1 is John
Name 2 is Paul
Name 3
is Steven
Name 4 is George
Name 5 is
David

I could use the following code:

$number = 5;
$x =
0;
while ($x < $number) {
$namenumber = $x +
1;
echo “Name $namenumber is
$names[$x]<br>”;
++$x;
}

As you can see, I can use the variable $x from my loop to print out the names in the array. You may have noticed I am also using the variable $namenumber which is always 1 greater than $x. This is because the array numbering starts from 0, so to number the names correctly in the output I must add one to the actual value.

PHP Tutorial - Part III

The Basics Of IF
If statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed.

IF Strucure
IF (something == something else)
{
THEN Statement
} else {
ELSE Statement
}

Variables
The most common use of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:
if ($username == “webmaster”)
which would compare the contents of the variable to the text string. The THEN section of code will only be executed if the variable is exactly the same as the contents of the quotation marks so if the variable contained ‘Webmaster’ or ‘WEBMASTER’ it will be false.

Constructing The THEN Statment
To add to your script, you can now add a THEN statement:
if ($username == “webmaster”){
echo “Please enter your password below”;
}

This will only display this text if the username is webmaster. If not, nothing will be displayed. You can actually leave an IF statement like this, as there is no actual requirement to have an ELSE part. This is especially useful if you are using multiple IF statements.

Constructing The ELSE Statement
Adding The ELSE statement is as easy as the THEN statement. Just add some extra code:
if ($username == “webmaster”) {
echo “Please enter your password below”;
} else{
echo “We are sorry but you are not a recognised user”;
}

Other Comparisons
There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g.
if ($enteredpass == $password)
You can also use the standard comparision symbols to check to see if one variable is greater than or less than another:

if ($age < “13″)
Or :
if ($date >$finished)
You can also check for multiple tests in one IF statement. For instance, if you have a form and you want to check if any of the fields were left blank you could use:
if ($name == “” || $email == “” || $password == “”) {
echo “Please fill in all the fields”;
}

PHP Tutorial - Part II

Printing Text
To output text in your PHP script is actually very simple. As with most other things in PHP, you can do it in a variety of different ways. The main one you will be using, though, is print. Print will allow you to output text, variables or a combination of the two so that they display on the screen.

The print statement is used in the following way:
print(”Hello world!”);
print is the command and tells the script what to do as with nearly every line in a PHP script, it must end in a semicolon. You would, of course, have to enclose this in your standard PHP tags, making the following code:

<?
print(”Hello world!”);
?>

Which will display: Hello world! on the screen.

Variables
As with other programming languages, PHP allows you to define variables. In PHP there are several variable types, but the most common is called a String. It can hold text and numbers. All strings begin with a $ sign. To assign some text to a string you would use the following code:
$welcome_text = “Hello and welcome to my website.”;
This is quite a simple line to understand.
Strings are case sensetive so $Welcome_Text is not the same as $welcome_text.
String names can contain letters, numbers and underscores but cannot begin with a number or underscore.
When assigning numbers to strings you do not need to include the quotes so:
$user_id = 987 would be allowed.

Outputting Variables
To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:

<?
$welcome_text = “Hello and welcome to my website.”;
print($welcome_text);
?>

Formatting Your Text
Everything is just output in the browser’s default font. It is very easy, though, to format your text using HTML. This is because, as PHP is a server side language, the code is executed before the page is sent to the browser. Thismeans that only the resulting information from the script is sent, so in the example above the browser would just be sent the text:
Hello and welcome to my website.
This means, though, that you can include standard HTML markup in your scripts and strings. The only problem with this is that many HTML tags require the ” sign. This means that you must tell the script which quotes should be used (the ones at the beginning and end of the output) and which ones should be ignored (the ones in the HTML code).

For this example I will change the text to the Arial font in red. The normal code for this would be:
<font face=”Arial” color=”#FF0000″>
</font>

As you can see this code contains 4 quotation marks so would confuse the script. Because of this you must add a backslash before each quotation mark to make the PHP script ignore it. The code would change to:

<font face=”Arial”color=”#FF0000″>

</font>

You can now include this in your print statement:

print(”<font face=”Arial” color”#FF0000″>Hello and welcome to my website.</font>”);

which will make the browser display:

Hello and welcome to my website.

because it has only been sent the code:

<font face=”Arial” color=”#FF0000″>Hello and welcome to my website.</font>