PHP Basics: Syntax, variables, data types, operators.
Here's an overview of PHP basics, covering syntax, variables, data types, and operators to get you started with the fundamentals.
1. PHP Syntax
PHP code is usually embedded in HTML and is written between <?php ... ?>
tags. Here’s an example of basic syntax:
<?phpecho "Hello, World!";?>
PHP statements end with a semicolon (;
), and comments can be written using:
//
for single-line comments/* ... */
for multi-line comments
2. Variables
Variables in PHP start with a dollar sign ($
) followed by the variable name. They are case-sensitive and don’t require explicit declaration of data types (PHP is loosely typed).
<?php$name = "Amir"; // String$age = 30; // Integer$price = 19.99; // Float?>
3. Data Types
PHP supports several data types:
String: A sequence of characters.
$greeting = "Hello, Amir!";
Integer: Whole numbers, both positive and negative.
$year = 2024;
Float: Numbers with a decimal point.
$pi = 3.14;
Boolean:
true
orfalse
.$isFrontendDeveloper = true;
Array: A collection of values.
$technologies = ["HTML", "CSS", "JavaScript"];
Object: Instance of a class.
class Developer { public $name; } $dev = new Developer();
NULL: Represents a variable with no value.
$emptyVar = NULL;
4. Operators
Arithmetic Operators
Addition (
+
)Subtraction (
-
)Multiplication (
*
)Division (
/
)Modulus (
%
)
<?php$result = 5 + 10; // 15?>
Assignment Operators
=
: Assigns a value.+=
: Adds and assigns.-=
: Subtracts and assigns.*=
: Multiplies and assigns./=
: Divides and assigns.
<?php$num = 10;$num += 5; // Now $num is 15?>
Comparison Operators
Equal (
==
)Identical (
===
- checks value and type)Not equal (
!=
or<>
)Not identical (
!==
)Greater than (
>
)Less than (
<
)Greater than or equal to (
>=
)Less than or equal to (
<=
)
<?php$a = 10;$b = 20;$isEqual = $a == $b; // false?>
Logical Operators
AND (
&&
)OR (
||
)NOT (
!
)
<?php$isFrontend = true;$isExperienced = true;$eligible = $isFrontend && $isExperienced; // true?>
With this foundation, you can start building basic scripts and programs in PHP!