PHP

PHP For Beginners

Invoke PHP in HTML:
<?php
echo "Hello world";
?>
PHP commands must end with a semicolon.
Single-line comment:
// This is a comment
Multi-line comment:
/* This is a section
of multiline comments
which will not be
interpreted */
Define a variable:
$x = 10;

Define a string variable:
$username = "Fred Smith";
Print variable on the screen without a return value:
echo $username;
Print variable on the screen with a return value:
print $username;
Code example:
<?php // test1.php
$username = "Fred Smith";
echo $username;
echo "<br>";
$current_user = $username;
echo $current_user;

Integer:
$count = 17;
Floating-point:
$count = 17.5;

Array of strings:
$team = array('Bill', 'Mary', 'Mike', 'Chris', 'Anne');
Two-dimensional array:
$oxo = array(array('x', ' ', 'o'),
array('o', 'o', 'x'),
array('x', 'o', ' '));

Is equal to:
$j == 4
Is not equal to:
$j != 21
$j <> 23
Is identical to:
$j === "987"
And:
$j == 3 && $k == 2 // High precedence
$j == 3 and $k == 2 // Low precedence
Or:
$j < 5 || $j > 10 // High precedence
$j < 5 or $j > 10 // Low precedence
Xor:
$j xor $k

Increment:
++$x;
$x++;
Decrement:
--$y;
$y++;
In if statement, ++$x == 10 means first increment x then compare it with 10, $x++ == 10 means first compare x with 10 then increment it.

Concatenate strings:
echo "You have " . $msgs . " messages.";
Append a string to a variable:
$bulletin .= $newsflash;

Without variable substitution (single quotes):
$info = 'Preface variables with a $ like this: $variable';
With variable substitution (double quotes):
echo "This week $count people have viewed your profile";

Escape quote:
$text = 'My spelling\'s still atroshus';
Tab:
$heading = "Date\tName\tPayment";

<?php
$author = "Steve Ballmer";
echo "Developers, developers, developers, developers, developers,
developers, developers, developers, developers!
- $author."
?>

<?php
$author = "Brian W. Kernighan";
echo <<<_END
Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it.
- $author.
_END;
?>
Remember that the closing _END; must appear right at the start of a new line, and it must be the only thing on that line.

PHP is a loosely typed langauge. This means that variables do not have to be declared before they are used and that PHP always converts variables to the type required by their context when they are accessed.
Automatic conversion from a number to a string:
$number = 12345 * 67890;
echo substr($number, 3, 1)
Copy link
On this page
Lecture
Basic Syntax
Variables
String
Numeric
Array
Operators
Variable Assignment
Variable Incrementing and Decrementing
String Concatenation
String Types
Escaping Characters
Multiline Commands
Multiline string
heredoc
Variable Typing