Saturday, July 18, 2009

PHP Basic

PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script is run on your web server, not on the user's browser, so you do not need to worry about compatibility issues. PHP is relatively new (compared to languages such as Perl (CGI) and Java)

PHP syntax

<?php
?>
---------------------------------------------------------
First PHP script

<html>
<body>

<?php
echo "Hello World";
?>

</body>
</html>

For display: Hello World using the PHP echo() statement.
-----------------------------------------------------------------------------
Comments in PHP
<?php
//This is a comment

/*
This is
a comment
block
*/
?>
----------------------------------------------------------------------------
PHP is a Loosely Typed Language

In PHP, a variable does not need to be declared before adding a value to it.

All variables in PHP start with a $ sign symbol.

$var_name = value;

<html>
<body>
<?php
$txt="Hello World! PHP";
$x=16;
echo $txt ;
?>
</body>
</html>

------------------------------------------------------------------------
* A variable name must start with a letter or an underscore "_"
* A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
* A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)


<html>
<body>

<?php
$txt1= "Hello World!";
$txt2="What a nice day!";
$txt3=strlen("Hello World!");
$txt4=strpos("Hello world!","world");
echo $txt1 . " " . $txt2 . " " . $txt3. " " . $txt4 ;

?>

</body>
</html>
----------------------------------
PHP Operators

+ Addition x=2 x+2
- Subtraction x=2
* Multiplication x=4
/ Division 15/5
% Modulus (division remainder) 5%2
++ Increment x=5 x++ x=6
-- Decrement x=5 x-- x=4

Assignment Operators
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y

Comparison Operators
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators
&& and x=6 y=3 (x < 10 && y > 1) returns true
|| or x=6 y=3 (x==5 || y==5) returns false
! not x=6 y=3 !(x==y) returns true

---------------------------------------------------------
IF

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
}
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
{
echo "Hello!<br />";
echo "Have a nice day!";
}
?>

</body>
</html>

------------------------------------------------------------------
SWITCH

<html>
<body>

<?php
switch ($x=1)
{
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";
}
?>

</body>
</html>

No comments:

Post a Comment