You are on page 1of 12

PHP is a owcrful iool for maling dynamic and inicraciivc Wcl agcs.

PHP is iIc
widcly-uscd, frcc, and cfficicni alicrnaiivc io comciiiors sucI as Microsofi's ASP.
In our PHP iuiorial you will lcarn aloui PHP, and Iow io cccuic scriis on your
scrvcr.
Basic PHP Syntax
A PHP scripting block always starts with 55 and ends with . A PHP scripting block can be
placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with ? and end with
?~.
For maximum compatibility, we recommend that you use the standard Iorm (?php) rather than
the shorthand Iorm.
?php
?~
A PHP Iile normally contains HTML tags, just like an HTML Iile, and some PHP scripting code.
Below, we have an example oI a simple PHP script which sends the text "Hello World" to the
browser:
html~
body~
?php
echo "Hello World";
?~
/body~
/html~

'ariables in PHP
Variables are used Ior storing values, like text strings, numbers or arrays. When a variable is
declared, it can be used over and over again in your script. All variables in PHP start with a $
sign symbol.
The correct way oI declaring a variable in PHP:
$varname value;
New PHP programmers oIten Iorget the $ sign at the beginning oI the variable. In that case it
will not work.
Let's try creating a variable containing a string, and a variable containing a number:
?php
$txt"Hello World!";
$x16;
?~

aming Rules for 'ariables
O A variable name must start with a letter or an underscore ""
O A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-
9, and )
O A variable name should not contain spaces. II a variable name is more than one word, it
should be separated with an underscore ($mystring), or with capitalization ($myString)

String 'ariables in PHP
String variables are used Ior values that contain characters.
AIter we create a string we can manipulate it. A string can be used directly in a Iunction or it can
be stored in a variable.
Below, the PHP script assigns the text "Hello World" to a string variable called $txt:
?php
$txt"Hello World";
echo $txt;
?~
The output oI the code above will be:
Hello World
Now, lets try to use some diIIerent Iunctions and operators to manipulate the string.

Te Concatenation O5erator
There is only one string operator in PHP.
The concatenation operator (.) is used to put two string values together.
To concatenate two string variables together, use the concatenation operator:
?php
$txt1"Hello World!";
$txt2"What a nice day!";
echo $txt1 . " " . $txt2;
?~
The output oI the code above will be:
Hello World! What a nice day!
II we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string (a space character), to separate the two strings.

Te strlen() function
The strlen() Iunction is used to return the length oI a string.
Let's Iind the length oI a string:
?php
echo strlen("Hello world!");
?~
The output oI the code above will be:
12

The length oI a string is oIten used in loops or other Iunctions, when it is important to know
when the string ends. (i.e. in a loop, we would want to stop the loop aIter the last character in the
string).

Te str5os() function
The strpos() Iunction is used to search Ior a character/text within a string.
II a match is Iound, this Iunction will return the character position oI the Iirst match. II no match
is Iound, it will return FALSE.
Let's see iI we can Iind the string "world" in our string:
?php
echo strpos("Hello world!","world");
?~
The output oI the code above will be:
6

Conditional Statements
Very oIten when you write code, you want to perIorm diIIerent actions Ior diIIerent decisions.
You can use conditional statements in your code to do this.
In PHP we have the Iollowing conditional statements:
O |f statement use Lhls sLaLemenL Lo execuLe some code only lf a speclfled condlLlon ls Lrue
O |fe|se statement use Lhls sLaLemenL Lo execuLe some code lf a condlLlon ls Lrue and anoLher
code lf Lhe condlLlon ls false
O |fe|se|fe|se statement use Lhls sLaLemenL Lo selecL one of several blocks of code Lo be
execuLed
O sw|tch statement use Lhls sLaLemenL Lo selecL one of many blocks of code Lo be execuLed

Te if Statement
&se the iI statement to execute some code only iI a speciIied condition is true.
Syntax
lf (cooJltloo% coJe to be execoteJ lf cooJltloo ls ttoe
The Iollowing example will output "Have a nice weekend!" iI the current day is Friday:
hLml
body
"php
$ddaLe(u%
lf ($dlrl% echo Pave a nlce weekend!
"
$body
$hLml

Te if...else Statement
&se the iI....else statement to execute some code iI a condition is true and another code iI a
condition is Ialse.
Syntax
lf (cooJltloo%
coJe to be execoteJ lf cooJltloo ls ttoe
else
coJe to be execoteJ lf cooJltloo ls folse
xample
The Iollowing example will output "Have a nice weekend!" iI the current day is Friday,
otherwise it will output "Have a nice day!":
hLml
body
"php
$ddaLe(u%
lf ($dlrl%
echo Pave a nlce weekend!
else
echo Pave a nlce day!
"
$body
$hLml
II more than one line should be executed iI a condition is true/Ialse, the lines should be enclosed
within curly braces:
hLml
body
"php
$ddaLe(u%
lf ($dlrl%

echo Pello!br $
echo Pave a nlce weekend!
echo See you on Monday!

"
$body
$hLml

Te PHP Switc Statement
&se the switch statement to select one oI many blocks oI code to be executed.
Syntax
swlLch (o%

case lobel1
coJe to be execoteJ lf olobel1
break
case lobel2
coJe to be execoteJ lf olobel2
break
defaulL
coJe to be execoteJ lf o ls Jlffeteot ftom botb lobel1 ooJ lobel2

This is how it works: First we have a single expression 3 (most oIten a variable), that is
evaluated once. The value oI the expression is then compared with the values Ior each case in the
structure. II there is a match, the block oI code associated with that case is executed. &se break
to prevent the code Irom running into the next case automatically. The deIault statement is used
iI no match is Iound.
xample
hLml
body
"php
swlLch ($x%

case 1
echo number 1
break
case 2
echo number 2
break
case 3
echo number 3
break
defaulL
echo no number beLween 1 and 3

"
$body
$hLml
at is an Array
A variable is a storage area holding a number or text. The problem is, a variable will hold only
one value.
An array is a special variable, which can store multiple values in one single variable.
II you have a list oI items (a list oI car names, Ior example), storing the cars in single variables
could look like this:
$cars1Saab
$cars2volvo
$cars38MW
In PHP, there are three kind oI arrays:
O -mer|c array An array wlLh a numerlc lndex
O ssoc|at|ve array An array where each lu key ls assoclaLed wlLh a value
O ,|t|d|mens|ona| array An array conLalnlng one or more arrays

umeric Arrays
A numeric array stores each array element with a numeric index.
There are two methods to create a numeric array.
1. In the Iollowing example the index are automatically assigned (the index starts at 0):
$carsarray(Saabvolvo8MW1oyoLa%
2. In the Iollowing example we assign the index manually:
$cars0Saab
$cars1volvo
$cars28MW
$cars31oyoLa
xample
In the Iollowing example you access the variable values by reIerring to the array name and
index:
"php
$cars0Saab
$cars1volvo
$cars28MW
$cars31oyoLa
echo $cars0 and $cars1 are Swedlsh cars
"
The code above will output:
Saab and volvo are Swedlsh cars


Associative Arrays
An associative array, each ID key is associated with a value.
When storing data about speciIic named values, a numerical array is not always the best way to
do it.
With associative arrays we can use the values as keys and assign values to them.
xample
In this example we use an array to assign ages to the diIIerent persons:
$ages array(eLer32 Cuagmlre30 !oe34%
xample
This example is the same as example 1, but shows a diIIerent way oI creating the array:
$ageseLer 32
$agesCuagmlre 30
$ages!oe 34
The ID keys can be used in a script:
"php
$ageseLer 32
$agesCuagmlre 30
$ages!oe 34
echo eLer ls $ageseLer years old
"
The code above will output:
eLer ls 32 years old

ultidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on.
xample
In this example we create a multidimensional array, with automatically assigned ID keys:
$famllles array
(
Crlfflnarray
(
eLer
Lols
Megan
%
Cuagmlrearray
(
Clenn
%
8rownarray
(
Cleveland
LoreLLa
!unlor
%
%
The array above would look like this iI written to the output:
Array
(
Crlffln Array
(
0 eLer
1 Lols
2 Megan
%
Cuagmlre Array
(
0 Clenn
%
8rown Array
(
0 Cleveland
1 LoreLLa
2 !unlor
%
%


xample
Lets try displaying a single value Irom the array above:
echo ls $famlllesCrlffln2
a parL of Lhe Crlffln famlly"
The code above will output:
ls Megan a parL of Lhe Crlffln famlly"
PHP Loo5s
OIten when you write code, you want the same block oI code to run over and over again in a
row. Instead oI adding several almost equal lines in a script we can use loops to perIorm a task
like this.
In PHP, we have the Iollowing looping statements:
O wh||e loops Lhrough a block of code whlle a speclfled condlLlon ls Lrue
O dowh||e loops Lhrough a block of code once and Lhen repeaLs Lhe loop as long as a speclfled
condlLlon ls Lrue
O for loops Lhrough a block of code a speclfled number of Llmes
O foreach loops Lhrough a block of code for each elemenL ln an array

Te wile Loo5
The while loop executes a block oI code while a condition is true.
Syntax
whlle (cooJltloo%

coJe to be execoteJ

xample
The example below deIines a loop that starts with i1. The loop will continue to run as long as i
is less than, or equal to 5. i will increase by 1 each time the loop runs:
hLml
body

"php
$l1
whlle($l3%

echo 1he number ls $l br $
$l++

"
$body
$hLml
Output:
1he number ls 1
1he number ls 2
1he number ls 3
1he number ls 4
1he number ls 3
Create a PHP Function
A Iunction will be executed by a call to the Iunction.
Syntax
funcLlon fooctlooNome(%

coJe to be execoteJ

PHP Iunction guidelines:
O Clve Lhe funcLlon a name LhaL reflecLs whaL Lhe funcLlon does
O 1he funcLlon name can sLarL wlLh a leLLer or underscore (noL a number%
xample
A simple Iunction that writes my name when it is called:
hLml
body
"php
funcLlon wrlLename(%

echo kal !lm 8efsnes


echo My name ls
wrlLename(%
"
$body
$hLml
Output:
My name ls kal !lm 8efsnes

PHP Functions - Adding 5arameters
To add more Iunctionality to a Iunction, we can add parameters. A parameter is just like a
variable.
Parameters are speciIied aIter the Iunction name, inside the parentheses.
xample
The Iollowing example will write diIIerent Iirst names, but equal last name:
hLml
body
"php
funcLlon wrlLename($fname%

echo $fname 8efsnesbr $

echo My name ls
wrlLename(kal !lm%
echo My slsLers name ls
wrlLename(Pege%
echo My broLhers name ls
wrlLename(SLale%
"
$body
$hLml
Output:
My name ls kal !lm 8efsnes
My slsLers name ls Pege 8efsnes
My broLhers name ls SLale 8efsnes

You might also like