1.
Introduction to PHP
PHP (Hypertext Preprocessor) is a widely-used, server-side scripting language
designed for web development.
It is embedded within HTML and used to create dynamic web pages.
Key features include:
o Open source.
o Compatibility with multiple databases (e.g., MySQL, PostgreSQL).
o Excellent for handling forms, cookies, and session management.
2. Conditional Constructs
Conditional constructs allow decision-making in PHP based on conditions.
Examples:
o if, else, elseif: Execute blocks of code based on a condition.
php
Copy code
if ($a > $b) {
echo "A is greater.";
} else {
echo "B is greater.";
}
o switch: Handles multiple conditions.
php
Copy code
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
default:
echo "Other days.";
}
3. Loops
Loops are used to execute a block of code repeatedly.
Types of Loops in PHP:
o for: Repeats a block for a specific number of times.
php
Copy code
for ($i = 0; $i < 5; $i++) {
echo $i;
}
o while: Runs while a condition is true.
php
Copy code
$i = 0;
while ($i < 5) {
echo $i++;
}
o do-while: Executes the block at least once.
o foreach: Iterates over arrays or objects.
php
Copy code
foreach ($array as $value) {
echo $value;
}
4. Functions
Functions are reusable blocks of code that perform specific tasks.
Syntax:
php
Copy code
function sayHello() {
echo "Hello!";
}
sayHello();
Functions can take parameters and return values.
php
Copy code
function add($a, $b) {
return $a + $b;
}
echo add(2, 3);
5. Arrays
Arrays store multiple values in a single variable.
Types of Arrays:
o Indexed Array: Uses numeric keys.
php
Copy code
$arr = ["Apple", "Banana", "Cherry"];
o Associative Array: Uses named keys.
php
Copy code
$arr = ["name" => "John", "age" => 25];
o Multidimensional Array: Contains nested arrays.
php
Copy code
$arr = [
["John", 25],
["Jane", 30]
];
6. Super Globals
Super global variables are built-in variables that are always accessible, regardless of
scope.
Examples:
o $_GET: Captures data sent via URL query strings.
o $_POST: Captures data sent via HTML forms.
o $_SESSION & $_COOKIE: Handle session and cookie data.
o $_SERVER: Provides information about the server and request.
7. Object-Oriented PHP
Object-Oriented Programming (OOP) organizes code into objects that encapsulate
data and behavior.
Key Concepts:
o Classes and Objects:
php
Copy code
class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
}
$car = new Car("Red");
echo $car->color;
o Inheritance: Classes can inherit properties and methods from other classes.
o Encapsulation: Controls access to data using public, private, and protected
modifiers.
o Polymorphism: Allows methods to behave differently in derived classes.
In Summary:
These topics provide the foundation for PHP programming, allowing developers to write
dynamic, interactive, and structured code. Let me know if you'd like examples or deeper
explanations for any section!