Basics
- Example 1: Printing “Hello, World!” using
echo
:
echo "Hello, World!";
- Example 2: Assigning and displaying variables:
$name = "John Doe";
echo "My name is " . $name;
- Example 3: Writing comments in PHP code:
// This is a single-line comment
/*
This is a
multi-line comment
*/
- Example 4: Using the
print
statement:
print "Welcome to PHP";
- Example 5: Getting the current date and time:
$currentDate = date("Y-m-d H:i:s");
echo "Current date and time: " . $currentDate;
Variables and Constants
- Example 1: Declaring and using variables:
$name = "John Doe";
$age = 25;
$salary = 5000.50;
echo "Name: " . $name . ", Age: " . $age . ", Salary: $" . $salary;
- Example 2: Defining and using constants:
define("PI", 3.14);
echo "The value of PI is: " . PI;
- Example 3: Variable scope (local and global):
$globalVariable = "I am a global variable";
function myFunction() {
$localVariable = "I am a local variable";
echo $localVariable;
echo $GLOBALS['globalVariable'];
}
myFunction();
- Example 4: Variable interpolation:
$name = "John Doe";
echo "My name is $name";
- Example 5: Constants case sensitivity:
define("MY_CONSTANT", "Hello");
echo MY_CONSTANT;
echo my_constant;
Operators
- Example 1: Arithmetic operators:
$num1 = 10;
$num2 = 5;
echo $num1 + $num2; // Addition
echo $num1 - $num2; // Subtraction
echo $num1 * $num2; // Multiplication
echo $num1 / $num2; // Division
echo $num1 % $num2; // Modulo
- Example 2: Assignment operators:
$num = 10;
$num += 5; // Equivalent to $num = $num + 5;
echo $num;
$str = "Hello";
$str .= " World"; // Equivalent to $str = $str . " World";
echo $str;
- Example 3: Comparison operators:
$num1 = 10;
$num2 = 5;
var_dump($num1 == $num2); // Equal to
var_dump($num1 != $num2); // Not equal to
var_dump($num1 > $num2); // Greater than
var_dump($num1 < $num2); // Less than
var_dump($num1 >= $num2); // Greater than or equal to
var_dump($num1 <= $num
2); // Less than or equal to
- Example 4: Logical operators:
$num1 = 10;
$num2 = 5;
$num3 = 7;
var_dump($num1 > $num2 && $num1 < $num3); // Logical AND
var_dump($num1 > $num2 || $num1 > $num3); // Logical OR
var_dump(!($num1 > $num2)); // Logical NOT
- Example 5: String operators:
$str1 = "Hello";
$str2 = "World";
echo $str1 . $str2; // Concatenation
echo $str1 .= $str2; // Concatenation and assignment
Conditionals
- Example 1: If-else statement:
$num = 10;
if ($num > 0) {
echo "The number is positive";
} else {
echo "The number is not positive";
}
- Example 2: Switch case statement:
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
default:
echo "Today is not Monday or Tuesday";
}
- Example 3: Ternary operator:
$num = 10;
$result = ($num % 2 == 0) ? "Even" : "Odd";
echo $result;
- Example 4: Multiple conditions in if statement:
$num = 10;
if ($num > 0 && $num < 20) {
echo "The number is between 0 and 20";
}
- Example 5: Nested if-else statements:
$num = 10;
if ($num > 0) {
if ($num < 20) {
echo "The number is between 0 and 20";
}
}
Loop Constructs
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
- Example 3: Do-while loop:
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 5);
- Example 4: Foreach loop with an array:
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
echo $number . " ";
}
- Example 5: Loop control statements (break and continue):
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop
}
if ($i % 2 == 0) {
continue; // Skip the rest of the iteration
}
echo $i . " ";
}
Arrays
- Example 1: Creating an indexed array:
$fruits = ["Apple", "Banana", "Orange"];
- Example 2: Accessing array elements:
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0]; // Output: Apple
- Example 3: Modifying array elements:
$fruits = ["Apple", "Banana", "Orange"];
$fruits[1] = "Mango";
- Example 4: Counting array elements:
$fruits = ["Apple", "Banana", "Orange"];
$count = count($fruits);
echo $count; // Output: 3
- Example 5: Searching for a value in an array:
$fruits = ["Apple", "Banana", "Orange"];
$index = array_search("Banana", $fruits);
echo $index; // Output: 1
Multi-Dimensional Arrays
- Example 1: Creating a 2D array:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
- Example 2: Accessing elements in a 2D array:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // Output: 6
- Example 3: Modifying elements in a 2D array:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$matrix[2][1] = 10;
- Example 4: Counting elements in a 2D array:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$count = count($matrix, COUNT_RECURSIVE);
echo $count; // Output: 9
- Example 5: Searching for a value in a 2D array:
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$index = array_search(6, array_merge(...$matrix));
echo $index; // Output: 5
Associative Arrays
- Example 1: Creating an associative array:
$student = [
"name" => "John Doe",
"age" => 20,
"city" => "New York"
];
- Example 2: Accessing values in an associative array:
$student = [
"name" => "John Doe",
"age" => 20,
"city" => "New York"
];
echo $student["name"];
// Output: John Doe
- Example 3: Modifying values in an associative array:
$student = [
"name" => "John Doe",
"age" => 20,
"city" => "New York"
];
$student["age"] = 21;
- Example 4: Counting elements in an associative array:
$student = [
"name" => "John Doe",
"age" => 20,
"city" => "New York"
];
$count = count($student);
echo $count; // Output: 3
- Example 5: Checking if a key exists in an associative array:
$student = [
"name" => "John Doe",
"age" => 20,
"city" => "New York"
];
$exists = array_key_exists("age", $student);
echo $exists; // Output: 1 (true)
Array of Associative Arrays
- Example 1: Creating an array of associative arrays:
$students = [
[
"name" => "John Doe",
"age" => 20,
"city" => "New York"
],
[
"name" => "Jane Smith",
"age" => 22,
"city" => "Los Angeles"
],
[
"name" => "Mike Johnson",
"age" => 19,
"city" => "Chicago"
]
];
- Example 2: Accessing values in an array of associative arrays:
$students = [
[
"name" => "John Doe",
"age" => 20,
"city" => "New York"
],
[
"name" => "Jane Smith",
"age" => 22,
"city" => "Los Angeles"
],
[
"name" => "Mike Johnson",
"age" => 19,
"city" => "Chicago"
]
];
echo $students[1]["name"]; // Output: Jane Smith
- Example 3: Modifying values in an array of associative arrays:
$students = [
[
"name" => "John Doe",
"age" => 20,
"city" => "New York"
],
[
"name" => "Jane Smith",
"age" => 22,
"city" => "Los Angeles"
],
[
"name" => "Mike Johnson",
"age" => 19,
"city" => "Chicago"
]
];
$students[2]["age"] = 20;
- Example 4: Counting elements in an array of associative arrays:
$students = [
[
"name" => "John Doe",
"age" => 20,
"city" => "New York"
],
[
"name" => "Jane Smith",
"age" => 22,
"city" => "Los Angeles"
],
[
"name" => "Mike Johnson",
"age" => 19,
"city" => "Chicago"
]
];
$count = count($students);
echo $count; // Output: 3
- Example 5: Searching for a value in an array of associative arrays:
$students = [
[
"name" => "John Doe",
"age" => 20,
"city" => "New York"
],
[
"name" => "Jane Smith",
"age" => 22,
"city" => "Los Angeles"
],
[
"name" => "Mike Johnson",
"age" => 19,
"city" => "Chicago"
]
];
$index = array_search("Los Angeles", array_column($students, "city"));
echo $index; // Output: 1
Functions
- Example 1: Creating a function:
function sayHello() {
echo "Hello, World!";
}
sayHello();
- Example 2: Function with parameters:
function greet($name) {
echo "Hello, " . $name . "!";
}
greet("John");
- Example 3: Returning a value from a function:
function add($num1, $num2) {
return $num1 + $num2;
}
$result = add(3, 5);
echo $result; // Output: 8
- Example 4: Function with default parameter value:
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
greet(); // Output: Hello, Guest!
greet("John"); // Output: Hello, John!
- Example 5: Recursive function:
function factorial($num) {
if ($num <= 1) {
return 1;
}
return $num * factorial($num - 1);
}
$result = factorial(5);
echo $result; // Output: 120
Classes
- Example 1: Creating a class:
class Person {
public $name;
public $age;
public function sayHello() {
echo "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
}
}
$person = new Person();
$person->name = "John";
$person->age = 25;
$person->sayHello();
- Example 2: Constructors and property accessors:
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$person = new Person("John", 25);
echo $person->getName(); // Output: John
echo $person->getAge(); // Output: 25
class Animal {
public function makeSound() {
echo "The animal makes a sound.";
}
}
class Dog extends Animal {
public function makeSound() {
echo "The dog barks.";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: The dog barks.
4: Static properties and methods:
class MathUtils {
public static $pi = 3.14159;
public static function square($num) {
return $num * $num;
}
}
echo MathUtils::$pi; // Output: 3.14159
echo MathUtils::square(5); // Output: 25
- Example 5: Abstract classes and interfaces:
abstract class Animal {
abstract public function makeSound();
}
interface CanFly {
public function fly();
}
class Bird extends Animal implements CanFly {
public function makeSound() {
echo "The bird chirps.";
}
public function fly() {
echo "The bird is flying.";
}
}
$bird = new Bird();
$bird->makeSound(); // Output: The bird chirps.
$bird->fly(); // Output: The bird is flying.
File Handling
- Example 1: Reading from a file:
$file = fopen("data.txt", "r");
while (!feof($file)) {
$line = fgets($file);
echo $line;
}
fclose($file);
- Example 2: Writing to a file:
$file = fopen("data.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
- Example 3: Appending to a file:
$file = fopen("data.txt", "a");
fwrite($file, "New content");
fclose($file);
- Example 4: Checking if a file exists:
if (file_exists("data.txt")) {
echo "File exists.";
} else {
echo "File does not exist.";
}
- Example 5: Deleting a file:
unlink("data.txt");
Database Connection (MySQL)
- Connecting to the database:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
- Selecting all users from the “users” table:
try {
$stmt = $conn->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($users as $user) {
echo "ID: " . $user['id'] . " - Name: " . $user['name'] . " - Age: " . $user['age'] . " - City: " . $user['city'] . " - Salary: " . $user['salary'] . "<br>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
- Deleting a user from the “users” table:
try {
$id = 1;
$stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
echo "User deleted successfully";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
- Adding a new user to the “users” table:
try {
$name = "John Doe";
$age = 25;
$city = "New York";
$salary = 5000;
$stmt = $conn->prepare("INSERT INTO users (name, age, city, salary) VALUES (:name, :age, :city, :salary)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':age', $age);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':salary', $salary);
$stmt->execute();
echo "New user added successfully";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
- Fetching a single user from the “users” table:
try {
$id = 1;
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
echo "ID: " . $user['id'] . " - Name: " . $user['name'] . " - Age: " . $user['age'] . " - City: " . $user['city'] . " - Salary: " . $user['salary'];
} else {
echo "User not found";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
Remember to replace “your_username”, “your_password”, and “your_database” with your actual MySQL credentials and database name. Additionally, ensure that PDO extension is enabled in your PHP configuration.