PHP Syntax Overview
PHP syntax is similar to C, Java,
and Perl, making it easy for beginners familiar with these languages. PHP code
is embedded in HTML and executed on the server to generate dynamic content.
Basic
PHP Tags
- Standard PHP tag
<?php
//
PHP code goes here
?>
- Short echo tag
<?=
"Hello, World!"; ?>
Note: Short tags <?
... ?> are discouraged unless short_open_tag is enabled in php.ini.
Statements
and Semicolons
- Each statement ends with a semicolon (;).
<?php
echo
"Hello, World!";
$name
= "Alice";
?>
Comments
in PHP |
||
Single-line |
// or # |
// This is a comment |
Multi-line |
/* ... */ |
/* This is a multi-line comment */ |
Variables
- Start with $
- Case-sensitive
- Can hold strings, numbers, arrays, objects, etc.
<?php
$age
= 25;
$name
= "John";
$isAdmin
= true;
?>
Data
Types
Type |
Description |
Example |
String |
Text |
"Hello" |
Integer |
Whole numbers |
100 |
Float / Double |
Decimal numbers |
10.5 |
Boolean |
True or False |
true |
Array |
Collection of values |
[1, 2, 3] |
Object |
Instance of a class |
new DateTime() |
Null |
No value |
null |
Constants
- Constants cannot change once defined.
<?php
define("PI",
3.14159);
echo
PI;
?>
Operators
Category |
Example |
Arithmetic |
+ - * / % |
Assignment |
= += -= *= /= |
Comparison |
== === != !== < > <= >= |
Logical |
`&& |
String |
. (concatenation) |
PHP
Code Inside HTML
<!DOCTYPE
html>
<html>
<body>
<h1>
<?php
$user = "Alice";
echo "Welcome, " . $user . "!";
?>
</h1>
</body>
</html>
- PHP runs on the server.
- Only the resulting HTML is sent to the browser.