Friday, December 28, 2007

Basic PHP

Basic PHP
A PHP scripting block always starts with "" . A PHP scripting block can be placed anywhere in the document.

Variables in PHP

$txt = "Hello World!";
$number = 16;


Strings in PHP

$txt="Hello World";
echo $txt;

The output of the code above will be:
Hello World

$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;

The output of the code above will be:
Hello World 1234

echo strlen("Hello world!");

The output of the code above will be:
12

echo strpos("Hello world!","world");

The output of the code above will be:
6

Conditional Statements

$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";

The Switch Statement

switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}

PHP Arrays
a.Numeric array - An array with a numeric ID key
b.Associative array - An array where each ID key is associated with a value
c.Multidimensional array - An array containing one or more arrays

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

The ID keys can be used in a script:

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";echo $names[1] . " and " . $names[2] .
" are ". $names[0] . "'s neighbors";

Looping
a.
$i=1;
while($i<=5)
{
echo "The number is " . $i . "
";
$i++;
}
b.
$i=0;
do
{
$i++;
echo "The number is " . $i . "
";
}
while ($i<5);
c.
for ($i=1; $i<=5; $i++)
{
echo "Hello World!
";
}

d.
$arr=array("one", "two", "three");foreach ($arr as $value)
{
echo "Value: " . $value . "
";
}

PHP Functions
1.
function writeMyName($fname)
{
echo $fname . " Refsnes.
";
}echo "My name is ";
writeMyName("Kai Jim");echo "My name is ";
writeMyName("Hege");echo "My name is ";
writeMyName("Stale");

2.
function writeMyName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "
";
}echo "My name is ";
writeMyName("Kai Jim",".");echo "My name is ";
writeMyName("Hege","!");echo "My name is ";
writeMyName("StĂĄle","...");

The output of the code above will be:
My name is Kai Jim Refsnes.
My name is Hege Refsnes!
My name is StĂĄle Refsnes...
3.
function add($x,$y)
{
$total = $x + $y;
return $total;
}echo "1 + 16 = " . add(1,16);

The output of the code above will be:
1 + 16 = 17

tutorial from http://www.w3schools.com/php/

Artikel yang Berkaitan

0 komentar:

Post a Comment