Your PHP code goes inside the
<?php
code here
?>
To display text in HTML output page
echo "this is output";
Make sure to end your line of PHP code with a semicolon
;
String Manipulations
<?php
$name = "Luke Perry";
echo strlen($name); // 10
echo substr($name, 0, 3); // Luk
echo strtoupper($name); // LUKE PERRY
echo strpos($name, "e Perry"); // 3
// concatenation
echo "hello" . "user";
?>
Variables
All variable names in PHP start with a dollar sign
$temp
Comment
comment is started with either of following code
//
or
#
Operators
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Conditional Sentence
if ( 2 > 10) {
echo " ok";
}
else if ( 2 == 33 ) {
echo "ccc";
}
else if ( 3 == 34) {
echo "this is 3";
}
else {
echo "nothing mathcn";
}
switch
switch (2) {
case 0:
echo 'The value is 0';
break;
case 1:
echo 'The value is 1';
break;
case 2:
echo 'The value is 2';
break;
default:
echo "The value isn't 0, 1 or 2";
}
Using or clause with switch
switch ($i) {
case 0:
echo '$i is 0.';
break;
case 1:
case 2:
case 3:
case 4:
case 5:
echo '$i is somewhere between 1 and 5.';
break;
case 6:
case 7:
echo '$i is either 6 or 7.';
break;
default:
echo "I don't know how much $i is.";
}
Working with Array
defining array and adding new element
<?php
// Add your array elements after
// "Beans" and before the final ")"
$array = array("Egg", "Tomato", "Beans" );
?>
<?php
$states = array();
$array = array_push($states, "Montana");
$array = array_push($states, "North Carolina");
$array = array_push($states, "California");
echo $array; // returns 3
var_dump($states);
?>
Pushing multiple elements together
<?php
$states = array(); // target array
$array = array_push($states,
"Montana",
"North Carolina",
"California");
echo $array; // returns 3
var_dump($games);
?>
Print array
<?php
echo $tens[2];
echo $tens{2};
?>
Modify and delete array element
$languages[1] = "green";
unset($array[2]);
unset($array);
Loop
foreach($languages as $lang) {
print "<p>$lang</p>";
}
another example
<?php
// Echoes the first five even numbers
for ($i = 2; $i < 11; $i = $i + 2) {
echo $i;
}
?>