Basic PHP Syntax
01. Closing/Opening Tags
A PHP scripting block starts with <?php
and ends with ?> and
it can be placed anywhere within a document. Each code line in PHP must
end with a semicolon. The semicolon is a separator and is used to distinguish
one set of instructions from another.
02. Output
There are two basic statements to output text with PHP:
echo and print.
<?php
echo "Hello World";
?>
|
<?php
print "Hello World";
?>
|
03. Variables
All variables in PHP start with a $
sign symbol. Variables may contain strings, numbers, or arrays. An example
of declaring variables can be written as follows:
<?php
$string = "this is a string";
echo "$string";
?>
|
04. Comments
Similar to Java, you can use comments as follows
1. // - is a simple, single
line comment eg:
2. /* */ - is the same as
a Java's/ C++ multiline comment eg:
/* multiline commnets
extend more than a few
lines */
|
05. Operators
There are several types of operators.They include: Assignment
Operators, Arithmetic Operators,
Comparison Operators, and
Logical Operators
|
Operator |
Example |
|
= |
$x = 5; |
Assignment |
+= |
$x += 5; |
x = x+5 |
-= |
$x -= 5; |
x = x - 5 |
/= |
$x /= 5; |
x = x/5 |
%= |
$x % = 5; |
x = x%5 |
.= |
$x .= "string"; |
Concatenation |
|
Operator |
Example |
|
+ |
$x = $x + 5; |
Addition |
- |
$x = $x - 5; |
Subtraction |
* |
$x = $x * 5; |
Multiplication |
/ |
$x = $x / 5; |
Division |
% |
$x = $x % 5; |
Modulus |
++ |
$x++; or ++$x; |
Increment |
-- |
$x--; or --$x; |
Decrement |
|
Operator |
Example |
|
== |
$x == $y; |
is equal to |
!= |
$x != $y; |
is NOT equal to |
< |
$x < $y; |
is less than |
> |
$x > $y; |
is greater than |
<= |
$x <= $y; |
is less than or equal to |
>= |
$x >= $y; |
is greater than or equal to |
|
Operator |
Example |
|
! |
!$x; |
TRUE if $x is NOT TRUE |
&& |
$x && $y; |
TRUE if both $x and $b are TRUE |
|| |
$x || $y; |
TRUE if either $x or $y is TRUE |
06. Conditionals
There are two basic conditional statements you can use.
They include switch statements
and if/else statements.
An example can be written as:
<?php
if ($x> $y)
echo "x is bigger than y";
?>
|
07. Looping
There are three types of loops you can use. They include
while loops, do/while
loops and for loops. An
example can be written as:
<?php
for ($x = 1; $x<= 10; $x++) {
echo $x;
}
?>
|
|