[go: up one dir, main page]

0% found this document useful (0 votes)
5 views18 pages

3. Decisions, Functions, String, Array & Exception Handling

The document provides an overview of key PHP programming concepts including decision-making with conditional statements, looping structures, functions, cookies, sessions, and error handling. It explains how to create and manipulate strings and arrays, as well as the use of built-in functions for common tasks. Additionally, it covers exception handling using try, catch, and throw statements to manage errors in a structured manner.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views18 pages

3. Decisions, Functions, String, Array & Exception Handling

The document provides an overview of key PHP programming concepts including decision-making with conditional statements, looping structures, functions, cookies, sessions, and error handling. It explains how to create and manipulate strings and arrays, as well as the use of built-in functions for common tasks. Additionally, it covers exception handling using try, catch, and throw statements to manage errors in a structured manner.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Decisions, Functions, String, Array & Exception Handling

1. Making Decisions in PHP


In PHP, decisions are made using conditional statements. These
statements allow you to check conditions and execute different
blocks of code based on those conditions.
 if Statement: Used to execute a block of code if the condition is
true.
if ($age >= 18) {
echo "You are an adult.";
}
 else Statement: Executes a block of code if the if condition is
false.
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
 elseif Statement: Used when you have multiple conditions to
check.
if ($age < 18) {
echo "You are a minor.";
} elseif ($age < 65) {
echo "You are an adult.";
} else {
echo "You are a senior.";
}
 switch Statement: A more efficient way to handle multiple
conditions that depend on the same variable.
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
default:
echo "Invalid day";
}

2. Doing Repetitive Tasks with Looping


PHP provides three main ways to repeat a block of code:
1. while loop
Executes as long as the condition is true.
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
2. do...while loop
Executes code once and then repeats as long as the condition is true.
$i = 1;
do {
echo $i . " ";
$i++;
} while ($i <= 5);
3. for loop
Executes a code block a specific number of times.
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
4. foreach loop
Used to iterate over arrays.
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . " ";
}
foreach with associative arrays
$ages = array("Peter" => 35, "Ben" => 37);
foreach ($ages as $name => $age) {
echo "$name is $age years old. ";
}
3. Mixing Decisions and Looping with HTML
You can combine conditions and loops to dynamically generate HTML
content based on certain conditions. This is useful when displaying
data dynamically from a database or form.
Example: Generating a Dynamic List Based on Conditions
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
echo "<ul>";
foreach ($fruits as $fruit) {
if ($fruit == "Mango") {
echo "<li><strong>$fruit</strong></li>";
} else {
echo "<li>$fruit</li>";
}
}
echo "</ul>";
?>
This will highlight "Mango" by making it bold.

4. What is a Function in PHP?


A function is a block of code designed to perform a specific task. You
can call this block of code when needed, making your code reusable
and organized.
Defining a Function:
function greet($name) {
echo "Hello, " . $name . "!";
}
greet("Alice"); // Output: Hello, Alice!
Returning Values from Functions:
function add($a, $b) {
return $a + $b;
}
echo add(5, 3); // Output: 8

5. Cookies in PHP
 What are Cookies?
 Cookies are small pieces of data stored on the client's browser,
created on the server-side. They are sent with each request to
the server, allowing the server to recognize the user.
 Usage: Set with setcookie(), accessed via $_COOKIE.
 Example:
Set a Cookie
setcookie("user", "Sonoo", time() + 3600); // Expires in 1 hour
 Access a Cookie
echo $_COOKIE["user"]; // Output: Sonoo if cookie is set
 Delete a Cookie
setcookie("user", "", time() - 3600); // Expires in the past to
delete
PHP $_COOKIE Superglobal:
 Use the $_COOKIE superglobal to retrieve cookie values:
$value = $_COOKIE["CookieName"];
Example of PHP Cookie (cookie1.php):
 Set Cookie and Check if it Exists:
<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
o First Request Output: "Sorry, cookie is not found!"
o After Refresh: "Cookie Value: Sonoo"

Sessions in PHP
 Definition: Used to store data across multiple pages for a single
user session.
 Usage: Started with session_start(), accessed via $_SESSION.
Example:
 Start a Session and Set Data
<?php
session_start();
$_SESSION["user"] = "Sachin";
echo "Session information is set.";
?>
 Retrieve Session Data
<?php
session_start();
echo "User is: " . $_SESSION["user"];
?>
 Session Counter
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo "Page Views: " . $_SESSION['counter'];
?>
 Destroy a Session
<?php
session_start();
session_destroy();
?>

7. In-built Functions in PHP


PHP has a vast library of in-built functions for performing common
tasks like string manipulation, mathematical operations, and array
handling.
 String Functions:
$str = "Hello World!";
echo strlen($str); // Outputs: 12 (length of the string)
echo strtoupper($str); // Outputs: HELLO WORLD!
 Array Functions:
$arr = [1, 2, 3];
array_push($arr, 4); // Adds 4 to the array
print_r($arr); // Outputs: [1, 2, 3, 4]

8. Creating and Accessing Strings


In PHP, strings can be created using single (') or double (") quotes.
Double quotes allow for variable interpolation.
Creating and Accessing Strings in PHP
1. Creating Strings
 Single-quoted Strings ('): The simplest way to define a string.
o Example:
$str1 = 'Hello, World!';
 Important: Variables and escape sequences (like \n)
will not be interpreted inside single-quoted strings.
 Double-quoted Strings ("): Allows variable interpolation and
escape sequences.
Example:
$name = 'John';
$str2 = "Hello, $name!";
// Output: Hello, John!
2. Accessing Strings
 By Index: Strings in PHP are arrays of characters, so individual
characters can be accessed using their index.
o Example:
$str = "Hello";
echo $str[0]; // Output: H
String Functions: There are several built-in functions to access or
manipulate strings:
 strlen(): Get the length of a string.
$length = strlen($str); // Output: 5
 strpos(): Find the position of the first occurrence of a substring.
$position = strpos($str, 'l'); // Output: 2
 substr(): Extract a portion of a string.
$substring = substr($str, 1, 3); // Output: ell
3. String Concatenation
 Using the . Operator: Concatenate two or more strings.
o Example:
$greeting = "Hello";
$name = "John";
$message = $greeting . ", " . $name . "!";
// Output: Hello, John!
4. String Interpolation
 Within Double Quotes: You can embed variables directly in
strings.
o Example:
$name = "John";
echo "Hello, $name!"; // Output: Hello, John!

9. Searching and Replacing Strings


PHP provides several functions to work with strings.
 strpos(): Finds the position of the first occurrence of a
substring.
$str = "Hello, World!";
echo strpos($str, "World"); // Outputs: 7
 str_replace(): Replaces all occurrences of a substring with
another string.
$str = "Hello, World!";
echo str_replace("World", "PHP", $str); // Outputs: Hello, PHP!

10. String Formatting


PHP offers multiple ways to format strings. This helps you present
data in a more readable way.
 sprintf(): Returns a formatted string.
$name = "Alice";
$greeting = sprintf("Hello, %s!", $name); // Outputs: Hello, Alice!
 printf(): Outputs a formatted string directly.
printf("The value is %.2f", 123.456); // Outputs: The value is 123.46

string-related library functions

PHP Arrays
Arrays in PHP allow you to store multiple values in a single variable.
Indexed Array
An array with numeric keys.
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
2. Associative Array
An array with named keys.
$ages = array("Peter" => 35, "Ben" => 37);
echo $ages["Peter"]; // Outputs: 35
3. Multidimensional Array
An array containing other arrays.
$students = array(
array("John", 18),
array("Jane", 19),
array("Jack", 20)
);
echo $students[1][0]; // Outputs: Jane

12. Accessing Array Elements


You can access array elements using their indices (for indexed arrays)
or keys (for associative arrays).
Accessing Indexed Array Elements:
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[2]; // Outputs: Cherry
Accessing Associative Array Elements:
$person = ["name" => "Alice", "age" => 25];
echo $person["age"]; // Outputs: 25

13. Looping Through Arrays


You can use loops to process arrays.
 Using foreach for Indexed Arrays:
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>"; // Outputs: Apple, Banana, Cherry
}
 Using foreach for Associative Arrays:
$person = ["name" => "Alice", "age" => 25];
foreach ($person as $key => $value) {
echo "$key: $value<br>"; // Outputs: name: Alice, age: 25
}

Looping with Associative Array in PHP


1. Using foreach() Loop:
The foreach() loop is the most common way to iterate over
associative arrays. It allows you to access both keys and values
directly.
Syntax:
foreach ($array as $key => $value) {
// Code to execute
}
Example:
<?php
$assoc_array = array("name" => "John", "age" => 25, "city" => "New
York");
foreach ($assoc_array as $key => $value) {
echo "$key: $value<br>";
}
?>
Output:
name: John
age: 25
city: New York
2. Using each() Function:
each() was traditionally used to iterate over arrays, but it is
deprecated as of PHP 7.2.0. It returns the current key/value pair from
an array and advances the array pointer.
Syntax:
each($array);
Example:
<?php
$assoc_array = array("name" => "John", "age" => 25, "city" => "New
York");

reset($assoc_array); // Reset pointer to the beginning of the array


while (list($key, $value) = each($assoc_array)) {
echo "$key: $value<br>";
}
?>
Output:
name: John
age: 25
city: New York
Note: Since each() is deprecated, it’s recommended to use foreach()
for better performance and compatibility.

Useful Library Functions in PHP


Some common library functions that are widely used in PHP:
 array_merge(): Merges two or more arrays into one.

$array1 = [1, 2];


$array2 = [3, 4];
$merged = array_merge($array1, $array2); // Result: [1, 2, 3, 4]
 explode(): Breaks a string into an array based on a delimiter.
$string = "apple,banana,orange";
$array = explode(",", $string); // Result: ["apple", "banana",
"orange"]
 implode(): Joins array elements into a string with a specified
delimiter.
$array = ["apple", "banana", "orange"];
$string = implode(", ", $array); // Result: "apple, banana, orange"
 in_array(): Checks if a value exists in an array.
$array = [1, 2, 3, 4];
$exists = in_array(3, $array); // Result: true
 array_keys(): Returns all the keys of an array.
$array = ["name" => "John", "age" => 25];
$keys = array_keys($array); // Result: ["name", "age"]

Understanding Exception and Error in PHP


Exceptions:
 Exceptions are used for handling errors in a more structured
and object-oriented way.
 They allow the program to continue running after an error,
without interrupting the flow of execution.
Errors:
 Errors are issues in the code that stop the execution, such as
syntax errors, missing functions, etc.
 Errors cannot be caught with try-catch (unless they are
converted into exceptions).

Try, Catch, and Throw in PHP


1. try Block:
The try block contains the code that may throw an exception.
2. catch Block:
The catch block handles the exception when it's thrown. It catches
the exception object and allows you to handle it.
3. throw Statement:
The throw keyword is used to manually throw an exception.
Syntax:
try {
// Code that might throw an exception
} catch (Exception $e) {
// Code to handle the exception
echo 'Caught exception: ' . $e->getMessage();
}
Example:
<?php
class CustomException extends Exception {}

try {
$number = -1;
if ($number < 0) {
throw new CustomException("Number must be positive");
}
} catch (CustomException $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
Output:
Caught exception: Number must be positive
Explanation:
 In the above example, the throw statement creates a
CustomException when $number is less than 0.
 The catch block handles the exception by printing the error
message using $e->getMessage().

You might also like