Learn PHP 1 to 6

Posted by Webmaster |

SAMs Teach Yourself PHP in 10 mins

Lesson 1

Remember to end every instruction with a semicolon ;

Special note. In order to display bits of code additional spaces have been inserted into some commands so they render as text. Look at the source code for the real stuff.

Page 7 – “Today is < ? php echo date(‘j F Y’); ? >”

Today is 12 January 2011


Page 8 –
The time is < ?php echo date(‘H:i:s’);?>
and the date is < ?php echo date(‘j F Y’);?>

The time is 22:58:26 and the date is 12 January 2011


Comment styles
Single line can be either // or #
Multiple line starts with /* and ends with */


Commenting a script
< ?php /* Time.php – or whatever your php page s called.
This script prints the current date
and time in the web browser.
*/
echo ‘The time is ‘;
echo date(‘H:i:s’); //Hours minutes & seconds
echo ‘and the date is ‘
echo date(‘j F Y’); #day, month and year
?>
The time is 22:58:26and the date is 12 January 2011


Lesson 2 – variables

Variables are always prefixed with a dollar ($) sign and start with a letter or underscore (used by ‘system’ variable. They do not need to be declared. They are case sensitive.

e.g. $FirstName, $_POST

Use ‘=’ to assign a variable to a value or an expression

$total = 2 * 8;

$FirstName = “Bob”;

Using variables in strings

A variable in a double quoted string uses its value.

A variable in a single quoted string uses its name.

< ?php $FirstName = “Bob”;
echo “Hello, $FirstName < br >”;
echo ‘Hello, $FirstName < br >’;
?>

Hello, Bob
Hello, $FirstName

You may need to delimit a variable, do this with braces {}.

< ?php $weight = 125 echo “The weight is {$weight}gms < br >” ? >

The weight is 125gms

Joining/ concatenating strings

Use the period to indicate concatenation.

< ?php

echo “The weight is “. $weight.”gms< br >”;

? >

The weight is 125gms

You can extend this to build a long string

< ?php

$mystring = “The weight is “;

$mystring .= $weight;

$mystring .= “gms< br >”;

echo $mystring;

? >

The weight is 125gms

Indirects or Variable Variables.

You can use the value of one variable to redirect to another variable.

< ?php
$weight = 125;
$name=”weight”;
echo “The value of the variable called ‘$name’ is ${$name} “;
?>

The value of the variable called ‘weight’ is 125


Lesson 3 – flow control

From here on we will assume the <?php tags in the descriptive text.

Conditional evaluations

$test=5; #set a value
if ($test < 10) # (test is inside round brackets)
{
echo “a is less than 10”;
}
# Execute code inside {} if TRUE
elseif ($test == 10) # if first test fails, then try this one

Note the comparison operator, see list below.

{
echo “a is equal to 10”;
}
# Execute code inside {} if second test is TRUE
else # otherwise
{
echo “a is greater than 10”;
}
# execute this code

a is less than 10

Comparison operators

Operator What it does
== is equal to
=== is equal to AND same data type
!= NOT equal to
!== NOT equal to AND same data type
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

Logical operators (in order of evaluation)

Operator What it does
!a NOT – TRUE if a is NOT TRUE
a && b AND – TRUE if both a AND b are TRUE
a || b OR – TRUE if either a OR b are TRUE
a and b AND – TRUE if both a AND b are TRUE
a xor b XOR – TRUE if either a OR b are TRUE, but NOT both
a or b OR – TRUE if either a OR b are TRUE

“switch” statement

Use this when making several clear comparisons, especially from a list.

$result=”Great”; # set up the comparison value
switch ($result) { # show which variable is being used
case “Average”:
case “Good”:
# either of these will trigger this condition
echo “You scored between 10 and 20 points.<br>”;
break; # make sure you skip all other code within the switch command
case “Great”: # next comparison
echo “You scored between 21 and 28 points.<br>”;
break;
case “Superb”:
echo “You scored over 28 points.<br>”;
break;
default:
echo “You scored less than 10 points.<br>”;
}
# if all else fails

You scored between 21 and 28 points.

Loops

There are three types of loops:-

  • WHILE
  • DO
  • FOR

WHILE

Code Note
$count = 1; # Initialise (assign) the loop variable
while ($count <= 10) { # set up the WHILE condition
$square = $count * $count; # Do the code within the {} for each iteration
echo “$count squared is $square <br>”;
$count++; # Alter the loop counter
}

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

DO

Code Note
$count = 1; # Initialise (assign) the loop variable
do { # Do the loop at least once
$square = $count * $count; # Do the code within the {} for each iteration
echo “$count squared is $square <br>”;
$count++; # Alter the loop counter
}while ($count <= 10) # test the WHILE condition

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

FOR

Works like WHILE

Code Note
for ($count = 1; $count <= 10; $count++) # set FOR parameters
# Initial value; final value; method of altering test variable at the end of each loop
{
$square = $count * $count;
echo “$count squared is $square <br>”;
# Do the code within the {} for each iteration
}

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

Breaking out of loops

Use BREAK; to end the iterations and continue from the next instruction or use CONTINUE; to stop this iteration and run the next one.


Lesson 4 – Functions

Use functions for repetitive or reusable tasks

Define a function

A function to calculate VAT.

Code Note
function VAT($xmount) { # Name of function and (arguments)
$VAT=$xmount * 0.175; # work out the result
return $VAT; # this is the value sent back
}

The price is 25
and the VAT is 4.38
giving a total of 29.38

Mail function & return values

Code Note
if (mail(“tony.lord@peoplefirst.co.uk”,”Hello”,”Test mail from the php page”,”from: pfs.php@peoplefirst.co.uk”)) { # mail is a built in function with arguments (destination, titles, message)
# and returns TRUE (1) if mail sent and FALSE (0) if not
echo “Email successful”; }
else
{ echo “Email not sent”; }

Email successful


Lesson 5 – numbers & maths

Increment and decrement

No = 1 = 1
No inc, then print = 2 ++$x
No print then inc = 2 $x++
Print No = 3 3
No dec then print = 2 –$x
No inc by 5 & print = 7 ($x +=5)
Note the brackets round compound expressions in strings.

Shortcuts/ Compound operators

x = 2 = 2
y = 5 = 5
Add, then print = 7 ($x += $y)
Subtract, then print = -3 ($x -= $y)
Same for * and /
Percent, then print = 2 ($x %= $y) (maybe works in php 5?)

Rounding numbers

The starting number is = 3.1415927.
Rounding up, answer = 4 uses function ceil($x)
Rounding down, answer = 3 uses function floor($x)

The starting number is = -3.1415927.
Rounding up, answer = -3 uses function ceil($x)
Rounding down, answer = -4 uses function floor($x)

The starting number is = 3.1415927.
Standard Rounding, answer = 3.14 uses function round($x,2)

The starting number is = 3.147.
Standard Rounding, answer = 3.15 uses function round($x,2)

Random numbers

This random integer is between 3 and 100 and is 57 using function rand($x,$y).
This random integer is between 3 and 100 and is 42 using function rand($x,$y).
This random integer is between 3 and 100 and is 86 using function rand($x,$y).
The highest random integer is and is found in the constant $RAND_MAX. (PHP 5?)


Lesson 6 – strings

For a full list of string functions see http://www.php.net/manual/en/ref.strings.php

String examples

This is a string example – ‘This is a string example’
This is a string example – “This is a string example”
This is a “string” example – This is a \”string\” example including escaped quote marks
Using variables – a $ in a double quoted string looks for the variable value,
within a single quoted string uses the literal.

Concatenating this ( $a = This is part one ) and this ( $b = and this is part two )
gives – This is part one and this is part two – using $a . $b

Compare strings using $a == $b for equality (N.B. case sensitive)
Compare strings using $a > $b (or <, >=, <=) for ASCII code values (N.B. case sensitive)

Formatting Strings

printf function gives simple formatting printing.

The boat has the number 4094 and a price of 2345.670000.

printf(“The %s has the number %d and a price of %f.” , $item , $number, $price );
where %s is a string variable, %d a decimal and %f a floating point one.
The order of the specified variables in the string corresponds to their position in the parameter section.

Format characters available for printf

Character Meaning
b Binary number
c Ascii character code
d Signed decimal integer
e Scientific notation
f Floating point
o Octal
s String
u Unsigned decimal integer
x Hex (lower case)
X Hex (UPPER CASE)

The boat has the number 4094 and a price of 2345.

printf(“The %s has the number %d and a price of %d.” , $item , $number, $price );
where %s is a string variable, %d are both decimal.

Alignment – padding

echo “< PRE >”;
printf (“%10s , %s \n”,$first,$second); right align 10 spaces
printf (“%-10s , %s”, $third, $fourth); left align 10 spaces
echo “< /PRE >”;

     First , Second
Third      , Fourth

Alignment – numbers

The price is 002345.67
printf (“The price is %09.2f”,$price);
The ‘0’ after the ‘%’ is the fill character,
the ‘9’ is the total length and
the 2 is the number of digits after the decimal point.

Formatted variables

The price is 002345.67

$formatprice = sprintf (“The price is %09.2f”,$price);
echo $formatprice

Capitalisation

$string = I love SailinG

I LOVE SAILING  – strtoupper ($string)
i love sailing  – strtolower ($string)
I love SailinG  – ucfirst ($string)
I Love SailinG  – ucwords ($string)
I Love Sailing  – ucwords (strtolower ($string))

Substrings

i love SailinG
ove S – select part of string (Starts at 0) – echo substr ($string,3,5)
inG – Selct from end – substr ($string,-3)
14 – Length of string – strlen($string)
4 – find “v” in string – strpos ($string, “v”)
ve SailinG – find “v” in string & extract to end – strstr ($string, “v”)