PHP Fundamentals: Loops, Cookies, Operators, and OOP
PHP foreach Loop Syntax and Usage
The foreach loop is specifically designed to iterate over elements in arrays.
Syntax Variations
1. Iterating over values only:
foreach ($array as $value) {
// statements using $value
}2. Iterating over keys and values:
foreach ($array as $key => $value) {
// statements using $key and $value
}Example: Iterating Colors
<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo $color . "<br>";
}
// This will print each color from the array.
?>Managing Cookies in PHP
A cookie is a small piece of data stored on the client’s browser. PHP uses cookies to store user information (like username or last visit time) across multiple page requests.
PHP handles cookies using the setcookie() function (to send/set a cookie) and the $_COOKIE superglobal array (to retrieve/access stored cookies).
Cookie Access Example
<?php
// Setting a cookie (e.g., for 1 hour)
// setcookie("username", "JohnDoe", time() + 3600, "/");
// Access cookie
if(isset($_COOKIE["username"])) {
echo "Welcome " . $_COOKIE["username"];
}
?>Essential PHP String Functions
PHP provides numerous built-in functions for manipulating strings. Here are two fundamental examples:
strlen($string)Returns the length of a string (number of characters).
Example:
echo strlen("Hello PHP"); // Output: 9strrev($string)Returns the reverse of a string.
Example:
echo strrev("Hello"); // Output: olleH
Other useful string functions include strtoupper(), strtolower(), and substr().
PHP Relational Operators
Relational operators are used to compare two values and return a boolean result (true or false).
| Operator | Meaning | Example ($x=5, $y=10) | Result |
|---|---|---|---|
== | Equal | $x == $y | false |
!= or <> | Not equal | $x != $y | true |
> | Greater than | $x > $y | false |
< | Less than | $x < $y | true |
>= | Greater than or equal to | $x >= $y | false |
<= | Less than or equal to | $x <= $y | true |
GET vs. POST HTTP Methods Comparison
The GET and POST methods are fundamental ways data is transferred from the client to the server in HTTP requests.
| Feature | GET Method | POST Method |
|---|---|---|
| Data Visibility | Yes (query string) | No |
| Data Size Limit | Limited (about 2000 characters) | Large |
| Security | Less secure | More secure |
| Use Cases | Bookmarking/search links | Submitting forms, passwords, file upload |
Menu-Driven Arithmetic Program in PHP
This script demonstrates a menu-driven program using PHP and HTML forms to perform basic arithmetic operations based on user selection.
PHP Processing Logic
<?php
if(isset($_POST['submit'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$op = $_POST['operation'];
$result = "";
switch($op){
case "add":
$result = $num1 + $num2;
break;
case "sub":
$result = $num1 - $num2;
break;
case "mul":
$result = $num1 * $num2;
break;
case "div":
$result = ($num2 != 0) ? $num1 / $num2 : "Cannot divide by zero";
break;
}
echo "<h4>Result: $result</h4>";
}
?>HTML Form Structure
<form method="post">
Enter Number 1: <input type="text" name="num1"><br><br>
Enter Number 2: <input type="text" name="num2"><br><br>
Select Operation:<br>
<select name="operation">
<option value="add">Addition</option>
<option value="sub">Subtraction</option>
<option value="mul">Multiplication</option>
<option value="div">Division</option>
</select><br>
<input type="submit" name="submit" value="Calculate">
</form>Object-Oriented Programming: Inheritance in PHP
Inheritance is a fundamental OOP feature that allows a class (the child class) to inherit properties and methods from another class (the parent class).
This mechanism significantly promotes code reuse and establishes an “is-a” relationship between classes.
PHP uses the extends keyword to implement inheritance.
Inheritance Example
<?php
class Animal {
public function sound() {
echo "Animal makes sound";
}
}
class Dog extends Animal {
// Overriding the parent method
public function sound() {
echo "Dog barks";
}
}
$dog = new Dog();
$dog->sound(); // Output: Dog barks
?>PHP Function to Reverse a Number
This PHP script defines a function to calculate the reverse of an integer using iterative division and modulo operations.
<?php
function reverseNumber($num) {
$rev = 0;
while($num > 0){
$digit = $num % 10;
$rev = ($rev * 10) + $digit;
$num = (int)($num / 10); // Ensure integer division
}
return $rev;
}
echo "Reverse: " . reverseNumber(12345); // Output: 54321
?>Conditional Execution: The PHP if…else Statement
The if...else statement is used for conditional execution, allowing different blocks of code to run based on whether a specified condition is true or false.
Syntax
if (condition) {
// code executes if condition is true
} else {
// code executes if condition is false
}Example: Checking Pass/Fail Status
<?php
$marks = 75;
if ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
// Output: Pass
?>Understanding PHP Array Types
PHP supports three main types of arrays, categorized by how their elements are indexed:
Indexed Arrays
Arrays with numeric indexes (starting from 0).
Example:
$colors = array("Red", "Green", "Blue");Associative Arrays
Arrays with named keys (strings) assigned to values.
Example:
$age = array("John" => 25, "Mary" => 30);Multidimensional Arrays
Arrays containing one or more arrays inside them, used to store complex data structures.
Example:
$students = array( array("John", 25, "A"), array("Mary", 30, "B") );
