Unit 4: Server Side Programming with PHP

By Notes Vandar

4.1 How PHP fits into a web page?

PHP (Hypertext Preprocessor) is a server-side scripting language designed specifically for web development. Unlike HTML, CSS, and JavaScript, which are processed in the user’s browser (client-side), PHP is executed on the web server before the resulting content is sent to the user’s browser. This makes PHP a powerful tool for generating dynamic web pages, managing data, and interacting with databases.

How PHP Works in Web Development:

  1. Server-Side Execution:
    • PHP scripts are executed on the server, and the server returns the generated HTML to the browser.
    • The user never sees the PHP code, only the resulting output, usually in HTML.
    • PHP can be embedded within HTML code, making it easy to integrate dynamic content into a webpage.
  2. Interaction with Databases:
    • PHP is often used to retrieve and display data from databases (e.g., MySQL, PostgreSQL).
    • It can send queries to the database, fetch data, and display it in the browser as HTML.
  3. Form Handling:
    • PHP can be used to process form submissions, validating and sanitizing user inputs, and performing actions like saving data to a database or sending emails.
  4. Dynamic Content Generation:
    • With PHP, web pages can change dynamically based on user input, session data, or other variables.
    • For example, PHP can display user-specific content based on login information or preferences stored in a database.

4.1.1 Embedding PHP in HTML

PHP is embedded into HTML by using PHP tags. PHP code is written between <?php ... ?> tags within the HTML document.

Example of PHP Embedded in HTML:

<!DOCTYPE html>
<html>
<head>
<title>PHP in HTML Example</title>
</head>
<body>
<h1>Welcome to My Website</h1>

<?php
// A simple PHP script to display the current date
echo “<p>Today is ” . date(“Y/m/d”) . “</p>”;
?>

<p>Thank you for visiting!</p>
</body>
</html>

Explanation:

  • The PHP code inside the <?php ... ?> tags is executed on the server.
  • The result (Today is 2024/10/07) is inserted into the HTML content, and only the HTML (along with the date) is sent to the user’s browser.
  • The user never sees the PHP code itself.

4.1.2 PHP as a Dynamic Content Generator

PHP can make a web page dynamic by generating content based on conditions, variables, or database values. For example, PHP can check user login status and display different content based on whether the user is logged in.

Example (Dynamic Welcome Message):

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Welcome Message</title>
</head>
<body>
<h1>Welcome to Our Website</h1><?php
// Display a dynamic welcome message
$username = “John”;

if ($username) {
echo “<p>Hello, ” . $username . “! Welcome back.</p>”;
} else {
echo “<p>Hello, guest! Please log in.</p>”;
}
?>
</body>
</html>

Explanation:

  • The PHP script checks if a username is available (e.g., after a user logs in).
  • Based on the condition, it displays a personalized message if the user is logged in, or a generic message for guests.

4.1.3 PHP Form Handling

PHP is often used to process HTML forms, capturing user input and performing actions like saving data or sending emails. This requires using the POST or GET methods to retrieve data from the form.

Example (Simple PHP Form Handling):

<!DOCTYPE html>
<html>
<head>
<title>Simple Form Example</title>
</head>
<body>
<h1>Contact Us</h1>

<form action=”submit_form.php” method=”POST”>
Name: <input type=”text” name=”name”><br>
Email: <input type=”email” name=”email”><br>
<input type=”submit” value=”Submit”>
</form>

<?php
// submit_form.php (PHP form processing script)
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$name = htmlspecialchars($_POST[‘name’]);
$email = htmlspecialchars($_POST[’email’]);

echo “<p>Thank you, $name. We have received your email: $email.</p>”;
}
?>
</body>
</html>

Explanation:

  • The form submits data to submit_form.php, which handles the form data.
  • PHP retrieves the submitted data using the $_POST superglobal array and then displays a thank you message with the user’s name and email.

4.1.4 PHP and Databases

PHP can connect to databases like MySQL, allowing you to retrieve, insert, update, and delete data. This makes PHP a great tool for creating database-driven websites (e.g., e-commerce sites, content management systems).

Example (Connecting PHP to a MySQL Database):

<?php
// Database connection
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “my_database”;

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}

// SQL query to retrieve data
$sql = “SELECT id, name, email FROM users”;
$result = $conn->query($sql);

// Display the data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo “ID: ” . $row[“id”] . ” – Name: ” . $row[“name”] . ” – Email: ” . $row[“email”] . “<br>”;
}
} else {
echo “0 results”;
}

$conn->close();
?>

Explanation:

  • This PHP script connects to a MySQL database and retrieves user data.
  • It checks if the connection is successful and then executes a SQL query to fetch data from the users table, displaying the results.

4.1.5 PHP for Session Management

PHP is often used for managing user sessions. A session stores data across different pages, like login information, to maintain user state.

Example (Session Management):

<?php
// Start a session
session_start();

// Set session variables
$_SESSION[“username”] = “JohnDoe”;
$_SESSION[“email”] = “john@example.com”;

echo “Session variables are set.”;
?>

  • In this example, PHP starts a session and sets session variables (username and email), which can be used across different pages.

4.1.6 PHP in a Full Stack Web Development Flow

PHP typically fits into a full-stack web development workflow in the following way:

  • Front-end: HTML, CSS, and JavaScript are used for designing the user interface and handling client-side interactivity.
  • Back-end: PHP is used to handle server-side logic, process requests, interact with databases, and dynamically generate HTML based on user interactions or database content.
  • Database: PHP communicates with databases (e.g., MySQL) to store and retrieve data.

PHP plays a vital role in bridging the gap between the front-end and back-end, turning static HTML into a dynamic and interactive user experience.

 

4.2 Variables and constants

In PHP, variables and constants are used to store data values that can be referenced and manipulated throughout a script. While variables can change during the execution of the program, constants, as the name suggests, remain the same once defined.


4.2.1 Variables

Variables in PHP are used to store data that can be changed or manipulated. They are identified by a dollar sign ($) followed by the variable name, and they can hold different types of data, such as strings, numbers, arrays, etc.

Characteristics of Variables in PHP:

  1. Must Start with $: All variables in PHP start with a dollar sign ($).
  2. Start with a Letter or Underscore: The first character of a variable must be a letter or an underscore, not a number.
  3. Case-Sensitive: Variables in PHP are case-sensitive ($age and $Age are two different variables).
  4. Dynamic Typing: PHP is a dynamically typed language, which means you do not need to declare the variable type explicitly.

Declaring and Assigning Values to Variables:

<?php
// Variable Declaration and Assignment
$firstName = “John”; // String
$age = 30; // Integer
$isMember = true; // Boolean
$height = 5.9; // Float

echo “Name: $firstName, Age: $age, Member: $isMember, Height: $height”;
?>

Variable Types:

  • String: A series of characters enclosed in quotes (" " or ' ').
  • Integer: Whole numbers, positive or negative.
  • Float: Decimal numbers.
  • Boolean: True or false values.
  • Array: Stores multiple values in a single variable.
  • Object: Represents an instance of a class.
  • NULL: Represents a variable with no value.

4.2.2 Variable Scope

The scope of a variable in PHP refers to the area of the code where the variable can be accessed. There are three types of variable scopes in PHP:

  1. Local Scope: Variables declared inside a function have local scope and can only be accessed within that function.
    <?php
    function testFunction() {
    $x = 10; // Local variable
    echo $x; // Accessible inside the function
    }
    testFunction();
    // echo $x; // Error: $x is not accessible outside the function
    ?>
  2. Global Scope: Variables declared outside of a function are in the global scope. They can be accessed anywhere in the script except inside functions, unless explicitly referenced with the global keyword.

    <?php
    $x = 100; // Global variable

    function testFunction() {
    global $x; // Use global variable
    echo $x; // Output: 100
    }
    testFunction();
    ?>

  3. Static Scope: The static keyword is used to retain the value of a variable across multiple function calls.
    <?php
    function counter() {
    static $count = 0;
    echo $count;
    $count++;
    }
    counter(); // Output: 0
    counter(); // Output: 1
    counter(); // Output: 2
    ?>

4.2.3 Constants

A constant in PHP is a value that, once defined, cannot be changed or undefined. Constants are used for values that remain the same throughout the execution of the script, such as configuration settings.

Characteristics of Constants:

  1. Defined Using define(): Constants are defined using the define() function.
  2. No $ Symbol: Unlike variables, constants do not start with a dollar sign ($).
  3. Global Scope: Constants have a global scope and can be accessed anywhere in the script.
  4. Case-Sensitive (by Default): Constants are case-sensitive by default, but can be made case-insensitive by passing true as the third argument in the define() function.

Defining and Using Constants:

<?php
// Defining a constant
define(“SITE_NAME”, “MyWebsite”);

// Displaying the constant value
echo SITE_NAME; // Output: MyWebsite

// Attempting to change the value will result in an error
// define(“SITE_NAME”, “NewWebsite”); // Error: Cannot redefine a constant
?>

Constants are Often Used for:

  • Configuration settings.
  • Application-wide values like API keys, database credentials, or application paths.

4.2.4 Predefined Constants

PHP also provides several predefined constants that can be used to access information about the environment, PHP version, file paths, and more.

Some Useful Predefined Constants:

  1. PHP_VERSION: The current PHP version.
    echo PHP_VERSION; // Outputs the current version of PHP
  2. FILE: The full path and filename of the file.
    echo __FILE__; // Outputs the full path of the current file
  3. LINE: The current line number of the file.
    echo __LINE__; // Outputs the current line number in the script
  4. PHP_OS: The operating system PHP is running on.
    echo PHP_OS; // Outputs the OS PHP is running on (e.g., Linux)

4.2.5 Difference Between Variables and Constants

Feature Variables Constants
Declaration Declared using $ (e.g., $name) Declared using define()
Changeable Value can be changed Value cannot be changed once defined
Case Sensitivity Case-sensitive Case-sensitive by default (can be case-insensitive)
Scope Local, global, or static scope Global scope
Syntax $variable = value; define("CONSTANT_NAME", value);

 

 

4.3 Operators in PHP

Operators in PHP are used to perform operations on variables and values. PHP supports a wide range of operators, which can be classified into different categories based on the type of operation they perform.


4.3.1 Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, etc.

Operator Name Example Result
+ Addition $a + $b Sum of $a and $b
- Subtraction $a - $b Difference of $a and $b
* Multiplication $a * $b Product of $a and $b
/ Division $a / $b Quotient of $a and $b
% Modulus $a % $b Remainder of $a / $b
** Exponentiation $a ** $b $a raised to the power of $b

Example:

<?php
$a = 10;
$b = 3;

echo $a + $b; // Output: 13
echo $a – $b; // Output: 7
echo $a * $b; // Output: 30
echo $a / $b; // Output: 3.3333
echo $a % $b; // Output: 1
echo $a ** $b; // Output: 1000 (10^3)
?>


4.3.2 Assignment Operators

Assignment operators are used to assign values to variables. The most common assignment operator is =.

Operator Name Example Equivalent To
= Simple Assignment $a = $b $a is assigned $b
+= Addition Assignment $a += $b $a = $a + $b
-= Subtraction Assignment $a -= $b $a = $a - $b
*= Multiplication Assign. $a *= $b $a = $a * $b
/= Division Assignment $a /= $b $a = $a / $b
%= Modulus Assignment $a %= $b $a = $a % $b

Example:

<?php
$a = 10;
$b = 5;

$a += $b; // $a is now 15 (10 + 5)
$a -= $b; // $a is now 10 (15 – 5)
$a *= $b; // $a is now 50 (10 * 5)
$a /= $b; // $a is now 10 (50 / 5)
$a %= $b; // $a is now 0 (10 % 5)
?>


4.3.3 Comparison Operators

Comparison operators are used to compare two values. They return a Boolean value (true or false).

Operator Name Example Result
== Equal $a == $b true if $a equals $b
=== Identical $a === $b true if $a is equal to $b and of the same type
!= Not Equal $a != $b true if $a is not equal to $b
<> Not Equal (alternate) $a <> $b true if $a is not equal to $b
!== Not Identical $a !== $b true if $a is not identical to $b
> Greater than $a > $b true if $a is greater than $b
< Less than $a < $b true if $a is less than $b
>= Greater than or equal to $a >= $b true if $a is greater than or equal to $b
<= Less than or equal to $a <= $b true if $a is less than or equal to $b

Example:

<?php
$a = 5;
$b = 10;

var_dump($a == $b); // Output: bool(false)
var_dump($a != $b); // Output: bool(true)
var_dump($a < $b); // Output: bool(true)
var_dump($a > $b); // Output: bool(false)
var_dump($a <= $b); // Output: bool(true)
var_dump($a >= $b); // Output: bool(false)
?>


4.3.4 Logical Operators

Logical operators are used to combine multiple conditions and return a Boolean value based on the logic of the conditions.

Operator Name Example Result
&& Logical AND $a && $b true if both $a and $b are true
` ` Logical OR
! Logical NOT !$a true if $a is false

Example:

<?php
$x = true;
$y = false;

var_dump($x && $y); // Output: bool(false)
var_dump($x || $y); // Output: bool(true)
var_dump(!$x); // Output: bool(false)
?>


4.3.5 Increment/Decrement Operators

These operators are used to increase or decrease the value of a variable by one.

Operator Name Example Description
++$a Pre-increment ++$a Increments $a by 1, then returns $a
$a++ Post-increment $a++ Returns $a, then increments $a by 1
--$a Pre-decrement --$a Decrements $a by 1, then returns $a
$a-- Post-decrement $a-- Returns $a, then decrements $a by 1

Example:

<?php
$a = 5;

echo ++$a; // Output: 6 (increments, then returns)
echo $a++; // Output: 6 (returns, then increments)
echo $a; // Output: 7
?>


4.3.6 String Operators

String operators are used to manipulate and concatenate strings.

Operator Name Example Result
. Concatenation $a . $b Concatenates $a and $b
.= Concatenation and Assignment $a .= $b Concatenates $b to $a and assigns it back to $a

Example:

<?php
$firstName = “John”;
$lastName = “Doe”;

echo $firstName . ” ” . $lastName; // Output: John Doe

$firstName .= ” Smith”;
echo $firstName; // Output: John Smith
?>


4.3.7 Ternary Operator

The ternary operator is a shorthand for an if-else statement.

Operator Name Example Result
?: Ternary Operator $a ? $b : $c Returns $b if $a is true, else $c

Example:

<?php
$firstName = “John”;
$lastName = “Doe”;

echo $firstName . ” ” . $lastName; // Output: John Doe

$firstName .= ” Smith”;
echo $firstName; // Output: John Smith
?>


4.3.8 Null Coalescing Operator (??)

The null coalescing operator checks if a value exists and is not null. If it is null, it returns a default value.

Operator Name Example Result
?? Null Coalescing Operator $a ?? $b Returns $a if it’s not null, otherwise returns $b

Example:

<?php
$age = 18;
$status = ($age >= 18) ? “Adult” : “Minor”;
echo $status; // Output: Adult
?>

4.3 Operators

PHP operators are used to perform operations on variables and values. These operations can include arithmetic, comparison, logic, assignment, and more. Operators in PHP are categorized based on their functionality.


4.3.1 Arithmetic Operators

Arithmetic operators are used for mathematical calculations like addition, subtraction, multiplication, etc.

Operator Name Example Result
+ Addition $a + $b Sum of $a and $b
- Subtraction $a - $b Difference of $a and $b
* Multiplication $a * $b Product of $a and $b
/ Division $a / $b Quotient of $a and $b
% Modulus $a % $b Remainder of $a / $b
** Exponentiation $a ** $b $a raised to the power of $b

Example:

<?php
$a = 15;
$b = 4;

echo $a + $b; // Output: 19
echo $a – $b; // Output: 11
echo $a * $b; // Output: 60
echo $a / $b; // Output: 3.75
echo $a % $b; // Output: 3
echo $a ** $b; // Output: 50625
?>


4.3.2 Assignment Operators

Assignment operators are used to assign values to variables.

Operator Name Example Equivalent To
= Simple Assignment $a = $b $a is assigned $b
+= Addition Assignment $a += $b $a = $a + $b
-= Subtraction Assignment $a -= $b $a = $a - $b
*= Multiplication Assignment $a *= $b $a = $a * $b
/= Division Assignment $a /= $b $a = $a / $b
%= Modulus Assignment $a %= $b $a = $a % $b

Example:

<?php
$a = 10;
$b = 5;

$a += $b; // $a becomes 15
$a -= $b; // $a becomes 10
$a *= $b; // $a becomes 50
$a /= $b; // $a becomes 10
$a %= $b; // $a becomes 0
?>


4.3.3 Comparison Operators

Comparison operators are used to compare two values. They return true or false based on the comparison.

Operator Name Example Result
== Equal $a == $b true if $a is equal to $b
=== Identical $a === $b true if $a equals $b and they are the same type
!= Not Equal $a != $b true if $a is not equal to $b
<> Not Equal (alt) $a <> $b true if $a is not equal to $b
!== Not Identical $a !== $b true if $a is not equal and not the same type as $b
> Greater than $a > $b true if $a is greater than $b
< Less than $a < $b true if $a is less than $b
>= Greater than or equal to $a >= $b true if $a is greater than or equal to $b
<= Less than or equal to $a <= $b true if $a is less than or equal to $b

Example:

<?php
$a = 10;
$b = 20;

var_dump($a == $b); // Output: bool(false)
var_dump($a != $b); // Output: bool(true)
var_dump($a > $b); // Output: bool(false)
var_dump($a < $b); // Output: bool(true)
?>


4.3.4 Logical Operators

Logical operators are used to combine conditional statements and return true or false.

Operator Name Example Result
&& Logical AND $a && $b true if both $a and $b are true
` ` Logical OR
! Logical NOT !$a true if $a is false, false if $a is true

Example:

<?php
$a = true;
$b = false;

var_dump($a && $b); // Output: bool(false)
var_dump($a || $b); // Output: bool(true)
var_dump(!$a); // Output: bool(false)
?>


4.3.5 Increment/Decrement Operators

These operators are used to increase or decrease the value of a variable by one.

Operator Name Example Result
++$a Pre-increment ++$a Increments $a by 1, then returns $a
$a++ Post-increment $a++ Returns $a, then increments $a by 1
--$a Pre-decrement --$a Decrements $a by 1, then returns $a
$a-- Post-decrement $a-- Returns $a, then decrements $a by 1

Example:

<?php
$a = 5;

echo ++$a; // Output: 6 (pre-increment)
echo $a++; // Output: 6 (post-increment)
echo $a; // Output: 7
?>


4.3.6 String Operators

String operators are used to manipulate strings in PHP.

Operator Name Example Result
. Concatenation $a . $b Concatenates $a and $b
.= Concatenation and Assignment $a .= $b Concatenates $b to $a and assigns it back to $a

Example:

<?php
$a = “Hello”;
$b = ” World”;

echo $a . $b; // Output: Hello World

$a .= ” Everyone”;
echo $a; // Output: Hello Everyone
?>


4.3.7 Ternary Operator

The ternary operator is a shorthand way to write simple if-else conditions.

Operator Name Example Result
?: Ternary Operator $a ? $b : $c Returns $b if $a is true, otherwise $c

Example:

<?php
$age = 18;
$status = ($age >= 18) ? “Adult” : “Minor”;

echo $status; // Output: Adult
?>


4.3.8 Null Coalescing Operator (??)

The null coalescing operator returns the first value that exists and is not null. If none are set, it returns the fallback value.

Operator Name Example Result
?? Null Coalescing Operator $a ?? $b Returns $a if $a is not null, otherwise returns $b

Example:

<?php
$name = null;
$defaultName = “Guest”;

echo $name ?? $defaultName; // Output: Guest
?>

4.4 Working with text and numbers

PHP provides numerous functions and techniques for handling text (strings) and numbers (integers and floating-point numbers). These operations are essential for various programming tasks such as manipulating user input, performing calculations, and formatting output.


4.4.1 Working with Text (Strings)

Strings in PHP can be created using single quotes (') or double quotes ("), and there are many built-in functions for manipulating strings.

1. Creating Strings

  • Single-quoted Strings: Literal string values where escape sequences like \n (new line) are not interpreted.
  • Double-quoted Strings: Escape sequences are interpreted, and variables within the string are expanded.

<?php
$singleQuoted = ‘Hello, World!’;
$doubleQuoted = “Hello, World!\n”;

echo $singleQuoted; // Output: Hello, World!
echo $doubleQuoted; // Output: Hello, World! (followed by a newline)
?>

2. String Concatenation

PHP uses the dot (.) operator to concatenate strings.

<?php
$greeting = “Hello”;
$name = “Alice”;

$fullGreeting = $greeting . “, ” . $name . “!”;
echo $fullGreeting; // Output: Hello, Alice!
?>

3. String Functions

PHP has a rich set of functions for manipulating strings:

  • strlen(): Returns the length of a string.
  • strtoupper(): Converts a string to uppercase.
  • strtolower(): Converts a string to lowercase.
  • substr(): Extracts a substring from a string.
  • trim(): Removes whitespace from both sides of a string.
  • strpos(): Finds the position of the first occurrence of a substring in a string.

<?php
$text = ” Hello, World! “;

echo strlen($text); // Output: 15
echo strtoupper($text); // Output: ” HELLO, WORLD! ”
echo substr($text, 2, 5); // Output: “Hello”
echo trim($text); // Output: “Hello, World!”
echo strpos($text, “World”); // Output: 9 (position of “World” in string)
?>


4.4.2 Working with Numbers

Numbers in PHP can be either integers or floats (decimal numbers). PHP provides arithmetic operations and several built-in functions to work with numbers.

1. Arithmetic Operations

PHP supports all basic arithmetic operations:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%): Returns the remainder of division.
  • Exponentiation (**): Raises a number to a power.

<?php
$a = 10;
$b = 3;

echo $a + $b; // Output: 13
echo $a – $b; // Output: 7
echo $a * $b; // Output: 30
echo $a / $b; // Output: 3.3333
echo $a % $b; // Output: 1
echo $a ** $b; // Output: 1000 (10^3)
?>

2. Number Functions

PHP has several functions for working with numbers:

  • abs(): Returns the absolute value of a number.
  • round(): Rounds a floating-point number to the nearest integer.
  • floor(): Rounds down to the nearest integer.
  • ceil(): Rounds up to the nearest integer.
  • max(): Returns the highest value among the numbers.
  • min(): Returns the lowest value among the numbers.

<?php
$number = -5.6;

echo abs($number); // Output: 5.6
echo round($number); // Output: -6
echo floor($number); // Output: -6
echo ceil($number); // Output: -5

echo max(10, 20, 30); // Output: 30
echo min(10, 20, 30); // Output: 10
?>


4.4.3 Type Casting

PHP automatically converts between types when necessary, but you can also explicitly cast between types using casting.

1. Casting to Integer

You can cast a string or float to an integer.

<?php
$floatNumber = 4.78;
$intNumber = (int)$floatNumber;

echo $intNumber; // Output: 4
?>

2. Casting to Float

<?php
$intNumber = 10;
$floatNumber = (float)$intNumber;

echo $floatNumber; // Output: 10
?>

3. Casting to String

<?php
$intNumber = 42;
$stringNumber = (string)$intNumber;

echo $stringNumber; // Output: “42”
?>


4.4.4 Formatting Numbers

PHP provides functions to format numbers for display, particularly useful when working with currency or decimal places.

1. number_format()

The number_format() function formats a number with grouped thousands and a specified number of decimal points.

<?php
$number = 12345.6789;

echo number_format($number, 2); // Output: 12,345.68
echo number_format($number, 0); // Output: 12,346 (no decimals)
?>


4.4.5 Working with Numeric Arrays

PHP allows you to store and manipulate multiple numbers using arrays.

1. Creating a Numeric Array

<?php
$numbers = [1, 2, 3, 4, 5];

print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
?>

2. Array Functions

  • count(): Returns the number of elements in an array.
  • array_sum(): Returns the sum of all values in an array.
  • sort(): Sorts an array in ascending order.

<?php
echo count($numbers); // Output: 5
echo array_sum($numbers); // Output: 15

sort($numbers);
print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
?>

4.5 Making decisions with control statements (if, switch, loop)

Control statements in PHP allow you to make decisions and repeat actions based on certain conditions. These include conditional statements like if, else, switch, and loops like for, while, and foreach.


4.5.1 Conditional Statements

1. if Statement

The if statement is used to execute code if a condition evaluates to true.

<?php
$age = 18;

if ($age >= 18) {
echo “You are eligible to vote.”;
}
?>

2. if-else Statement

The if-else statement adds an alternative block of code that will execute if the condition is false.

<?php
$age = 16;

if ($age >= 18) {
echo “You are eligible to vote.”;
} else {
echo “You are not eligible to vote.”;
}
?>

3. if-elseif-else Statement

The if-elseif-else statement allows you to check multiple conditions and execute corresponding code blocks.

<?php
$marks = 85;

if ($marks >= 90) {
echo “Grade: A+”;
} elseif ($marks >= 80) {
echo “Grade: A”;
} elseif ($marks >= 70) {
echo “Grade: B”;
} else {
echo “Grade: C”;
}
?>

4. Ternary Operator

The ternary operator is a shorthand for if-else conditions.

<?php
$age = 18;
$status = ($age >= 18) ? “Adult” : “Minor”;

echo $status; // Output: Adult
?>


4.5.2 switch Statement

The switch statement is used when you want to execute one of several blocks of code based on the value of a variable.

<?php
$day = “Monday”;

switch ($day) {
case “Monday”:
echo “Start of the work week!”;
break;
case “Friday”:
echo “Almost the weekend!”;
break;
case “Sunday”:
echo “Relax, it’s the weekend!”;
break;
default:
echo “Just another day!”;
}
?>

  • break: Terminates the switch block, preventing the execution of the following case blocks.
  • default: Executes if no cases match.

4.5.3 Loops

Loops allow you to repeat code multiple times.

1. while Loop

The while loop continues as long as the condition is true.

<?php
$i = 1;

while ($i <= 5) {
echo “Number: $i<br>”;
$i++;
}
?>

2. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once, as the condition is checked after the block.

<?php
$i = 1;

do {
echo “Number: $i<br>”;
$i++;
} while ($i <= 5);
?>

3. for Loop

The for loop is used when the number of iterations is known beforehand.

<?php
for ($i = 1; $i <= 5; $i++) {
echo “Number: $i<br>”;
}
?>
  • Initialization: $i = 1; – sets the starting value of the loop counter.
  • Condition: $i <= 5; – loop runs as long as this condition is true.
  • Increment/Decrement: $i++ – increases the value of $i after each iteration.

4. foreach Loop

The foreach loop is designed for iterating over arrays. For each element in the array, the code block is executed.

<?php
$fruits = [“Apple”, “Banana”, “Cherry”];

foreach ($fruits as $fruit) {
echo $fruit . “<br>”;
}
?>


4.5.4 Control Statements for Loops

  • break: Used to exit a loop or switch statement early.
  • continue: Skips the current iteration of a loop and proceeds to the next iteration.

break Example:

<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break; // Exits the loop when $i is 3
}
echo “Number: $i<br>”;
}
?>

continue Example:

<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skips the iteration when $i is 3
}
echo “Number: $i<br>”;
}
?>

4.6 Working with arrays, strings, datetime and files

PHP provides robust functionality for working with arrays, strings, dates/times, and files. These operations are essential for handling complex data structures, manipulating textual content, dealing with dates, and reading/writing files in PHP applications.


4.6.1 Working with Arrays

An array in PHP is a data structure that stores multiple values. PHP supports several functions to work with arrays effectively.

1. Creating Arrays

Arrays in PHP can be indexed or associative:

  • Indexed Array: Keys are integers (default index starts from 0).
    <?php
    $fruits = [“Apple”, “Banana”, “Orange”];
    ?>
  • Associative Array: Keys are strings.
    <?php
    $person = [
    “name” => “John”,
    “age” => 30,
    “city” => “New York”
    ];
    ?>

2. Common Array Functions

  • count(): Returns the number of elements in an array.
    echo count($fruits); // Output: 3
  • array_merge(): Merges two or more arrays.
    $arr1 = [1, 2, 3];
    $arr2 = [4, 5, 6];
    $merged = array_merge($arr1, $arr2);
    print_r($merged); // Output: [1, 2, 3, 4, 5, 6]
  • array_push(): Adds one or more elements to the end of an array.
    $arr1 = [1, 2, 3];
    $arr2 = [4, 5, 6];
    $merged = array_merge($arr1, $arr2);
    print_r($merged); // Output: [1, 2, 3, 4, 5, 6]
  • in_array(): Checks if a value exists in an array.
    echo in_array(“Apple”, $fruits); // Output: 1 (true)
  • array_keys(): Returns all the keys of an array.
    print_r(array_keys($person)); // Output: [“name”, “age”, “city”]

3. Looping through Arrays

You can use foreach to loop through arrays:

<?php
foreach ($fruits as $fruit) {
echo $fruit . “<br>”;
}

foreach ($person as $key => $value) {
echo “$key: $value<br>”;
}
?>


4.6.2 Working with Strings

PHP offers many built-in functions for manipulating strings. Here are some of the most commonly used string functions.

1. String Functions

  • strlen(): Returns the length of a string.
    $text = “Hello, World!”;
    echo strlen($text); // Output: 13
  • str_replace(): Replaces occurrences of a substring with another substring.
    $newText = str_replace(“World”, “PHP”, $text);
    echo $newText; // Output: Hello, PHP!
  • substr(): Returns a part of a string.
    echo substr($text, 7, 5); // Output: World
  • strpos(): Finds the position of the first occurrence of a substring in a string.
    echo strpos($text, “World”); // Output: 7
  • trim(): Removes whitespace from both sides of a string.
    $name = ” John “;
    echo trim($name); // Output: “John”

2. Concatenating Strings

Use the dot (.) operator to concatenate strings.

<?php
$firstName = “John”;
$lastName = “Doe”;

$fullName = $firstName . ” ” . $lastName;
echo $fullName; // Output: John Doe
?>


4.6.3 Working with Date and Time

PHP provides the DateTime class and several date/time functions to work with dates and times.

1. Getting the Current Date and Time

  • date(): Formats a local date and time.
    echo date(“Y-m-d H:i:s”); // Output: current date and time (e.g., 2024-10-08 12:34:56)
  • time(): Returns the current Unix timestamp.
    echo time(); // Output: e.g., 1696788496

2. Working with DateTime

The DateTime class provides a more flexible way to handle date and time.

  • Creating a DateTime object:
    $now = new DateTime();
    echo $now->format(‘Y-m-d H:i:s’); // Output: current date and time
  • Modifying DateTime:
    $now->modify(‘+1 day’);
    echo $now->format(‘Y-m-d’); // Output: date of tomorrow
  • Date Difference:

    $startDate = new DateTime(‘2024-01-01’);
    $endDate = new DateTime(‘2024-12-31’);
    $interval = $startDate->diff($endDate);

    echo $interval->days; // Output: number of days between the two dates

3. Date Functions

  • strtotime(): Parses an English textual datetime into a Unix timestamp.
    $timestamp = strtotime(‘next Monday’);
    echo date(‘Y-m-d’, $timestamp); // Output: date of the next Monday

4.6.4 Working with Files

PHP allows you to create, read, write, and delete files using several built-in functions.

1. Opening and Reading a File

  • fopen(): Opens a file for reading or writing.
  • fread(): Reads the contents of a file.
  • fclose(): Closes the file after reading.

<?php
$file = fopen(“example.txt”, “r”);

if ($file) {
while (($line = fgets($file)) !== false) {
echo $line; // Output each line from the file
}
fclose($file);
} else {
echo “Unable to open the file.”;
}
?>

2. Writing to a File

  • fwrite(): Writes data to a file.

<?php
$file = fopen(“example.txt”, “w”);

if ($file) {
fwrite($file, “Hello, World!\n”);
fwrite($file, “This is a new line.”);
fclose($file);
} else {
echo “Unable to open the file.”;
}
?>

3. File Handling Functions

  • file_exists(): Checks if a file exists.
    if (file_exists(“example.txt”)) {
    echo “File exists.”;
    }
  • unlink(): Deletes a file.
    if (unlink(“example.txt”)) {
    echo “File deleted.”;
    } else {
    echo “File deletion failed.”;
    }

4.7 Functions

Functions in PHP are blocks of reusable code that perform a specific task. They help organize and reduce repetition in your code, improving maintainability and readability.


4.7.1 Defining and Calling Functions

Defining a Function

A function in PHP is defined using the function keyword followed by the function name, a set of parentheses (for parameters), and curly braces {} containing the code block.

<?php
function greet() {
echo “Hello, World!”;
}
?>

Calling a Function

Once a function is defined, you can call it by writing its name followed by parentheses.

<?php
greet(); // Output: Hello, World!
?>

4.7.2 Functions with Parameters

Parameters allow you to pass data into functions. You can specify parameters within the parentheses of the function definition.

Single Parameter

<?php
function greet($name) {
echo “Hello, $name!”;
}

greet(“Alice”); // Output: Hello, Alice!
?>

Multiple Parameters

Functions can accept multiple parameters, separated by commas.

<?php
function add($a, $b) {
return $a + $b;
}

echo add(5, 10); // Output: 15
?>


4.7.3 Return Values

Functions can return values using the return statement. The returned value can be used in further operations.

<?php
function multiply($a, $b) {
return $a * $b;
}

$result = multiply(5, 10);
echo $result; // Output: 50
?>

If a function doesn’t explicitly return a value, it returns NULL by default.


4.7.4 Default Parameters

You can set default values for parameters. If the function is called without an argument for that parameter, the default value is used.

<?php
function greet($name = “Guest”) {
echo “Hello, $name!”;
}

greet(); // Output: Hello, Guest!
greet(“John”); // Output: Hello, John!
?>


4.7.5 Variable Scope

  • Local Scope: Variables defined within a function are local to that function and cannot be accessed outside.

    <?php
    function test() {
    $message = “Hello from the function!”;
    echo $message;
    }

    test(); // Output: Hello from the function!
    echo $message; // Error: Undefined variable $message
    ?>

  • Global Scope: Variables declared outside of functions are global and can be accessed anywhere except inside functions unless specified with the global keyword.

    <?php
    $message = “Hello from outside!”;

    function test() {
    global $message;
    echo $message; // Accessing the global variable
    }

    test(); // Output: Hello from outside!
    ?>


4.7.6 Passing Arguments by Reference

By default, function parameters are passed by value, meaning changes made to the parameter within the function do not affect the original variable. However, you can pass parameters by reference using the & symbol, which allows the function to modify the original variable.

<?php
function addFive(&$number) {
$number += 5;
}

$originalNumber = 10;
addFive($originalNumber);
echo $originalNumber; // Output: 15
?>

4.7.7 Anonymous Functions (Closures)

Anonymous functions are functions without a name. They are often used as callbacks or for short-term tasks.

<?php
$greet = function($name) {
echo “Hello, $name!”;
};

$greet(“Alice”); // Output: Hello, Alice!
?>

Anonymous functions can also use variables from the parent scope with the use keyword.

<?php
$prefix = “Hello”;
$greet = function($name) use ($prefix) {
echo “$prefix, $name!”;
};

$greet(“Alice”); // Output: Hello, Alice!
?>


4.7.8 Recursive Functions

A recursive function is a function that calls itself. It is useful for solving problems like traversing trees or calculating factorials.

<?php
function factorial($n) {
if ($n == 0) {
return 1;
} else {
return $n * factorial($n – 1);
}
}

echo factorial(5); // Output: 120
?>

 

Important Questions
Comments
Discussion
0 Comments
  Loading . . .