Comprehensive Guide to PHP Elements

1. Introduction to PHP
PHP (Hypertext Preprocessor) is a widely-used open-source scripting language designed primarily for web development. It runs on the server side and is embedded into HTML, making it an essential language for dynamic and interactive web applications.
2. Basic Syntax
PHP scripts start with <?php
and end with ?>
. Statements end with a semicolon (;
).
<?php
echo "Hello, World!";
?>
Case Sensitivity
-
Keywords (e.g.,
if
,else
,while
) are not case-sensitive. -
Variable names are case-sensitive.
3. Variables
Variables store data and are defined using the $
symbol.
$name = "John";
$age = 30;
Variable Scope
-
Local: Declared inside a function, accessible only within.
-
Global: Declared outside functions, can be accessed using
global
or$GLOBALS
. -
Static: Retains value between function calls.
-
Superglobal: Special predefined variables like
$_POST
,$_GET
.
4. Data Types
PHP supports multiple data types:
-
String:
"Hello"
-
Integer:
123
-
Float:
3.14
-
Boolean:
true/false
-
Array:
array("apple", "banana")
-
Object: Defined from a class.
-
NULL: Represents no value.
-
Resource: Holds references to external resources like database connections.
5. Operators
Arithmetic Operators
$sum = 5 + 3; // Addition
$sub = 5 - 3; // Subtraction
$mul = 5 * 3; // Multiplication
$div = 5 / 3; // Division
$mod = 5 % 3; // Modulus
Comparison Operators
$a == $b // Equal
$a === $b // Identical (same value & type)
$a != $b // Not equal
$a < $b // Less than
$a > $b // Greater than
Logical Operators
$a && $b // AND
$a || $b // OR
!$a // NOT
Assignment Operators
$x += 5; // Equivalent to $x = $x + 5;
$x -= 5; // Equivalent to $x = $x - 5;
6. Control Structures
Conditional Statements
if ($age > 18) {
echo "Adult";
} elseif ($age == 18) {
echo "Just turned adult";
} else {
echo "Minor";
}
Switch Statement
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Friday":
echo "Weekend coming";
break;
default:
echo "Regular day";
}
Loops
// While loop
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
// For loop
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
// Foreach loop (for arrays)
$fruits = ["apple", "banana"];
foreach ($fruits as $fruit) {
echo $fruit;
}
7. Functions
User-defined functions enhance code reusability.
function greet($name) {
return "Hello, " . $name;
}
echo greet("Alice");
8. Arrays
Arrays store multiple values in a single variable.
Indexed Array
$colors = ["red", "blue", "green"];
echo $colors[0]; // Outputs "red"
Associative Array
$ages = ["Alice" => 25, "Bob" => 30];
echo $ages["Alice"]; // Outputs 25
Multidimensional Array
$students = [
["John", 20],
["Jane", 22]
];
echo $students[0][0]; // Outputs "John"
9. Strings
String manipulation is essential in PHP.
$name = "John Doe";
echo strlen($name); // String length
echo str_replace("Doe", "Smith", $name); // Replace substring
10. Superglobals
PHP provides predefined global arrays:
-
$_GET
– Collects data from a form (via URL parameters). -
$_POST
– Collects form data via HTTP POST. -
$_SESSION
– Stores user session data. -
$_COOKIE
– Stores user cookies.
11. File Handling
$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);
12. Object-Oriented Programming (OOP)
Class & Object
class Car {
public $brand;
function __construct($brand) {
$this->brand = $brand;
}
function getBrand() {
return $this->brand;
}
}
$myCar = new Car("Toyota");
echo $myCar->getBrand();
13. Error Handling
try {
throw new Exception("Error occurred");
} catch (Exception $e) {
echo $e->getMessage();
}
14. Database Connection (MySQLi)
$conn = new mysqli("localhost", "root", "", "testdb");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
15. Sessions and Cookies
Session
session_start();
$_SESSION["user"] = "John Doe";
echo $_SESSION["user"];
Cookie
setcookie("username", "John", time() + (86400 * 30), "/");
PHP is a versatile language for web development, offering features like database interaction, OOP, and security mechanisms. Mastering these elements allows developers to build robust and efficient web applications.