PHP Introduction

1.Hello World example

Use any of your favourite text editor and type your first php code and save it with “helloWorld.php”. Upload it to your web server and then execute it.


echo “Hello World”;


to execute : http://www.yourserver.com/helloWorld.php ( place it in the root directory )

semicolon means end of a line.


2.Conditional Check if..else

check for a condition to be true or false. Why do you need to check for conditions? Take a scenario like this. If you are checking the site in the morning I should say "Good morning", so how do we handle this now.


// if time is less than 12'o clock the site would display
// "Good Morning"
if($time < 12)
echo "Good Morning";


How do we say good evening now?

if($time < 12)
echo "Good Morning";
else // time is more than 12
echo "Good Evening";






Where are those curly braces? If you use one statement just after the if ..condition then you don't need it but if you have more than one line then you shuld open and close curly braces.


eg:
if($time < 12) {
echo "Good Morning";
$num_of_visits = $num_of_visits + 1;
}




3.Looping

Loop is used to repeat a job as many time you want

while loop


$i=1;
while($i<5) {
echo “Hello World”.$i;
}


The above code snippet would display
Hello World 1Hello World 2Hello World 3Hello World 4


for…loop


for($i=0; $i<5; $i++)
echo $i;



The loop will display 01234 as output.



do…while

some times you need your loop to execute at least once regardless of condition


$x = 5;
do {
echo “Hello World”;
}while($x<5);


though x=5 initially, the loop would execute once because the conditional statement is at the end. When it reaches the end the condition x<5 returns false the loop will not execute any more.

0 comments



Some Links (off programming)