Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

PHP Conditional Statements:

Conditional statements in PHP are programming constructs that allow you to execute different
blocks of code based on whether a certain condition is true or false. These statements provide
the ability to control the flow of execution in a PHP script. The primary conditional statements in
PHP are:

In PHP we have these conditional statements:

• if Statement.
• if-else Statement
• If-else if-else Statement
• Switch statement
1. if statement: It evaluates a condition and executes a block of code if the condition is true.
Optionally, an else block can be included to execute a different block of code when the
condition is false.
Syntax:

if (condition) {

// code to execute if condition is true

Example:

<?php

$x = "22";

if ($x < "20") {

echo "Hello World!";

?>
2. if-else if-else statement: This allows you to add additional conditions to check if the initial
condition is false. It's often used when there are multiple conditions to evaluate.

Syntax:

if (condition1) {

// code to execute if condition1 is true

} elseif (condition2) {

// code to execute if condition1 is false and condition2 is true

} else {

// code to execute if both condition1 and condition2 are false

Example:

<?php

$x = "22";

if ($x == "22") {

echo "correct guess";

} else if ($x < "22") {

echo "Less than 22";

} else {

echo "Greater than 22";

?>
3. if-else statement: This is used with the if statement to specify a block of code to be
executed if the condition is false.
Syntax:

if (condition) {

// code to execute if condition is true

} else {

// code to execute if condition is false

Example:

<?php

$x = "22";

if ($x < "20") {

echo "Less than 20";

} else {

echo "Greater than 20";

?>

4. switch statement: It allows for multi-way branching, providing a more concise way to write
several else-if statements. It evaluates an expression and executes code blocks based on
matching cases.
Syntax:

switch (expression) {

case value1:

// code to execute if expression equals value1

break;

case value2:
// code to execute if expression equals value2

break;

default:

// code to execute if expression doesn't match any case

Example:

<?php

$i = "2";

switch ($i) {

case 0:

echo "i equals 0";

break;

case 1:

echo "i equals 1";

break;

case 2:

echo "i equals 2";

break;

default:

echo "i is not equal to 0, 1 or 2";

?>
The `?` operator: is known as the ternary operator in PHP. It provides a compact way to
express conditional logic within an expression. Its syntax is as follows:

Syntax:

(condition) ? true_expression : false_expression;

Here's how it works:

- The `condition` is evaluated.

- If the condition is true, the `true_expression` is executed.

- If the condition is false, the `false_expression` is executed.

For example:

$age = 25;

$message = ($age >= 18) ? "You are an adult" : "You are a minor";

echo $message; // Output: "You are an adult"

In this example:

- If `$age` is greater than or equal to 18, the message "You are an adult" is assigned
to the `$message` variable.

- If `$age` is less than 18, the message "You are a minor" is assigned to the
`$message` variable.

The ternary operator is often used for simple conditional assignments where you
want to assign a value to a variable based on a condition.
PHP Iterative Statements: Iterative statements are used to run same block of code over and over
again for a certain number of times.

In PHP, we have the following loops:

• while Loop
• do-while Loop
• for Loop
• foreach loop

1. While Loop

The While loop in PHP is used when we need to execute a block of code again and again based
on a given condition. If the condition never becomes false, the while loop keeps getting
executed. Such a loop is known as an infinite loop.

Syntax:

while (condition) {

// code to be executed while the condition is true

In a while loop:

• The condition is evaluated before each iteration of the loop.


• If the condition evaluates to true, the code inside the loop is executed.
• After executing the code inside the loop, the condition is evaluated again. If it still evaluates
to true, the loop continues. If it evaluates to false, the loop terminates, and the program
continues with the code after the loop.

Example:

<?php

$x = 1;

while($x <= 10) {

echo "The number is: $x <br>";

$x++;
}

?>

2. Do-While Loop

The do-while loop is similar to a while loop except that it is guaranteed to


execute at least once. After executing a part of a program for once, the rest of
the code gets executed based on a given boolean condition.

Syntax:

do {

// code to be executed

} while (condition);
In a do-while loop:

• The code block is executed once before the condition is checked.


• If the condition evaluates to true, the code block is executed again, and the process
repeats.
• The loop continues executing as long as the condition remains true.

Example:

<?php

$x =10;

do {

echo "The number is: $x <br>";

$x++;

} while ($x <= 9);

?>
3. For Loop: The for loop is used to iterate a block of code multiple times.

Syntax:

for (initialization; condition; increment/decrement) {

// code to be executed

In a for loop:

• The initialization part is executed once at the beginning of the loop. It's typically used to
initialize a loop control variable.
• The condition part is evaluated before each iteration of the loop. If it evaluates to true, the
loop continues; otherwise, the loop terminates.
• The increment/decrement part is executed after each iteration of the loop. It's typically
used to modify the loop control variable.
• The code block inside the loop is executed as long as the condition remains true.

Example:

<?php

for ($x = 0; $x <= 10; $x++) {

echo "The number is: $x <br>";

?>

4. Foreach loop

The foreach loop in PHP can be used to access the array indexes in PHP. It only works on arrays
and objects.

Syntax:

foreach ($array_or_object as $key => $value) {

// code to be executed

}
In a foreach loop:

• $array_or_object is the array or object that you want to iterate over.


• $key is an optional variable that holds the current key of the array or property name of the
object.
• $value is a variable that holds the current value associated with the key in the array or the
value of the property in the object.
• The code block inside the loop is executed once for each element in the array or property in
the object.

Example:

<?php

echo "Welcome to the world of foreach loops <br>";

$arr = array("Bananas", "Apples", "Harpic", "Bread", "Butter");

foreach ($arr as $value) {

echo "$value <br>";

?>
Arrays: arrays are a fundamental data structure used to store multiple values in a single variable.
PHP arrays can hold values of different types and can be indexed by integers or strings

Types of Arrays

1. Indexed Arrays: Arrays with numeric indices.


2. Associative Arrays: Arrays with named keys.
3. Multidimensional Arrays: Arrays containing one or more arrays.

Creating and Using Arrays


Indexed Arrays: Indexed arrays are arrays where each element is assigned a numeric index. The
indices usually start at 0 and increase by one for each element.

<?php

// Creating an indexed array

$fruits = array("Apple", "Banana", "Orange");

// Accessing elements

echo $fruits[0]; // Outputs: Apple

// Adding an element

$fruits[] = "Grapes"; // Adds "Grapes" at the next available index

// Looping through an indexed array

foreach ($fruits as $index => $fruit) {

echo "Index $index: $fruit\n";

?>

Output:

Index 0: Apple

Index 1: Banana

Index 2: Orange

Index 3: Grapes
Associative Arrays: Associative arrays are arrays where each element is associated with a named
key instead of a numeric index. These keys can be strings.

<?php

// Creating an associative array

$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);

// Accessing elements

echo $age["Peter"]; // Outputs: 35

// Adding an element

$age["Sara"] = 25; // Adds the key "Sara" with value 25

// Looping through an associative array

foreach ($age as $name => $age) {

echo "$name is $age years old.\n";

?>

Output:

Peter is 35 years old.

Ben is 37 years old.

Joe is 43 years old.

Sara is 25 years old.

Multidimensional Arrays: Multidimensional arrays are arrays that contain one or more arrays as
elements. These arrays can be indexed or associative arrays.

<?php

// Creating a multidimensional array

$contacts = array(

"John" => array(


"email" => "john@example.com",

"phone" => "123-456-7890"

),

"Jane" => array(

"email" => "jane@example.com",

"phone" => "098-765-4321"

);

// Accessing elements

echo $contacts["John"]["email"]; // Outputs: john@example.com

// Looping through a multidimensional array

foreach ($contacts as $name => $contact) {

echo "$name's email is " . $contact["email"] . " and phone number is " . $contact["phone"] .
".\n";

?>

Output:

John's email is john@example.com and phone number is 123-456-7890.

Jane's email is jane@example.com and phone number is 098-765-4321.


Accessing and manipulating arrays:

Accessing Array Elements

Indexed Arrays

You can access elements in an indexed array using their numeric indices.

<?php

$fruits = array("Apple", "Banana", "Orange");

// Accessing elements

echo $fruits[0]; // Outputs: Apple

echo $fruits[1]; // Outputs: Banana

echo $fruits[2]; // Outputs: Orange

?>

Associative Arrays

Access elements in an associative array using their named keys.

<?php

$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);

// Accessing elements

echo $ages["Peter"]; // Outputs: 35

echo $ages["Ben"]; // Outputs: 37

echo $ages["Joe"]; // Outputs: 43

?>
Multidimensional Arrays

Access elements in a multidimensional array by chaining indices or keys.

<?php

$contacts = array(

"John" => array(

"email" => "john@example.com",

"phone" => "123-456-7890"

),

"Jane" => array(

"email" => "jane@example.com",

"phone" => "098-765-4321"

);

// Accessing elements

echo $contacts["John"]["email"]; // Outputs: john@example.com

echo $contacts["Jane"]["phone"]; // Outputs: 098-765-4321

?>

Manipulating Array Elements

Adding Elements

You can add elements to an array by specifying a key (for associative arrays) or leaving the key
empty (for indexed arrays).

Indexed Arrays

<?php

$fruits = array("Apple", "Banana");


// Adding an element

$fruits[] = "Orange"; // Adds "Orange" at the next available index

// Adding an element at a specific index

$fruits[3] = "Grapes";

?>

Associative Arrays

<?php

$ages = array("Peter" => 35, "Ben" => 37);

// Adding an element

$ages["Joe"] = 43;

// Adding or updating an element

$ages["Peter"] = 36; // Updates Peter's age to 36

?>

Multidimensional Arrays

<?php

$contacts = array(

"John" => array(

"email" => "john@example.com",

"phone" => "123-456-7890"

);

// Adding an element

$contacts["Jane"] = array(

"email" => "jane@example.com",


"phone" => "098-765-4321"

);

// Adding a nested element

$contacts["John"]["address"] = "123 Main St";

?>

Updating Elements

Update elements by assigning a new value to an existing key.

Indexed Arrays

<?php

$fruits = array("Apple", "Banana", "Orange");

// Updating an element

$fruits[1] = "Grapes"; // Changes "Banana" to "Grapes"

?>

Associative Arrays

<?php

$ages = array("Peter" => 35, "Ben" => 37);

// Updating an element

$ages["Peter"] = 36; // Changes Peter's age to 36

?>
array functions:

1. count(): Returns the number of elements in an array.

$arr = [1, 2, 3, 4, 5];

echo count($arr); // Output: 5

2. array_push(): Pushes one or more elements onto the end of an array.

$arr = [1, 2, 3];

array_push($arr, 4, 5);

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

3. array_pop(): Removes and returns the last element from an array.

$arr = [1, 2, 3, 4, 5];

$last = array_pop($arr);

echo $last; // Output: 5

4. array_shift(): Removes and returns the first element from an array.

$arr = [1, 2, 3, 4, 5];

$first = array_shift($arr);

echo $first; // Output: 1

5. array_unshift(): Adds one or more elements to the beginning of an array.

$arr = [2, 3, 4];

array_unshift($arr, 1);

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

6. array_slice(): Extracts a portion of an array.

$arr = [1, 2, 3, 4, 5];

$subset = array_slice($arr, 2, 2);

print_r($subset); // Output: Array ( [0] => 3 [1] => 4 )


7. array_merge(): Combines the elements of one or more arrays together.

$arr1 = ['a', 'b'];

$arr2 = ['c', 'd'];

$merged = array_merge($arr1, $arr2);

print_r($merged); // Output: Array ( [0] => a [1] => b [2] => c [3] => d )

8. array_search(): Searches an array for a given value and returns the corresponding key if
successful.

$arr = ['a' => 1, 'b' => 2, 'c' => 3];

$key = array_search(2, $arr);

echo $key; // Output: b

9. array_key_exists(): Checks if the specified key exists in the array.

$arr = ['a' => 1, 'b' => 2, 'c' => 3];

if (array_key_exists('b', $arr)) {

echo 'Key "b" exists!';

} else {

echo 'Key "b" does not exist!';

// Output: Key "b" exists!

10. array_values(): Returns all the values of an array as a new array.

$arr = ['a' => 1, 'b' => 2, 'c' => 3];

$values = array_values($arr);

print_r($values); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 )

11. array_keys(): Returns all the keys of an array as a new array.

$arr = ['a' => 1, 'b' => 2, 'c' => 3];

$keys = array_keys($arr);
print_r($keys); // Output: Array ( [0] => a [1] => b [2] => c )

12. array_reverse(): Reverses the order of elements in an array.

$arr = [1, 2, 3, 4, 5];

$reversed = array_reverse($arr);

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

Type casting: In PHP, casting refers to the conversion of one data type to another. There are two
types of casting: implicit casting and explicit casting.

1. Implicit Casting:

Implicit casting happens automatically by PHP when it's needed to perform an operation or
comparison involving different data types. PHP tries to convert one type to another implicitly
based on context. For example:

$x = 10; // integer

$y = 5.5; // float

$result = $x + $y; // Implicit casting: float + integer -> float

echo $result; // Output: 15.5

2. Explicit Casting:

Explicit casting involves manually converting one data type to another using specific casting
functions or operators. This allows you to control the type conversion explicitly. PHP provides
several casting methods:

- (int) or intval(): Converts a value to an integer.

- (float) or floatval(): Converts a value to a float.

- (string) or strval(): Converts a value to a string.

- (bool) or boolval(): Converts a value to a boolean.

```php

$floatValue = 5.7;
$intValue = (int) $floatValue; // Explicit casting: float -> integer

echo $intValue; // Output: 5

In this example, the float value `5.7` is explicitly cast to an integer using `(int)`.

Include and require:

Include:The `include` statement includes and evaluates the specified file. If the file is not found, a
warning is issued, but the script will continue execution.

<?php

// Including a file

include 'header.php';

echo "This is the main content of the page.";

include 'footer.php';

?>

- If the file cannot be found, `include` will emit a warning (E_WARNING) but the script will
continue to execute.

- Useful for including non-essential files, where the rest of the script can still run even if the file is
missing.

require:The `require` statement includes and evaluates the specified file. If the file is not found, a
fatal error is issued, and the script will stop execution.

<?php

// Requiring a file

require 'config.php';

echo "This is the main content of the page.";

?>

- If the file cannot be found, `require` will emit a fatal error (E_COMPILE_ERROR) and stop the
execution of the script.

- Useful for including essential files, where the script cannot run without them.
include_once:The `include_once` statement includes and evaluates the specified file during the
execution of the script. This behavior is similar to `include`, except that if the file has already been
included, it will not be included again.

<?php

// Including a file only once

include_once 'header.php';

echo "This is the main content of the page.";

include_once 'header.php'; // This will not include 'header.php' again

include 'footer.php';

?>

Prevents multiple inclusions of the same file, which can help avoid function redefinitions, variable
reassignment, or other potential conflicts.

Issues a warning if the file cannot be found but continues script execution.

require_once

The `require_once` statement includes and evaluates the specified file during the execution of the
script. This behavior is similar to `require`, except that if the file has already been included, it will
not be included again.

<?php

// Requiring a file only once

require_once 'config.php';

echo "This is the main content of the page.";

require_once 'config.php'; // This will not include 'config.php' again

?>

- Prevents multiple inclusions of the same file, ensuring the file is included only once.

- Emits a fatal error and stops script execution if the file cannot be found.
include vs. require

- Use `include` when the file is not critical to the application, allowing the script to continue even
if the file is missing.

- Use `require` when the file is essential for the application, ensuring the script stops if the file is
missing.

include_once vs. require_once

- Use `include_once` to include non-essential files only once, avoiding multiple inclusions.

- Use `require_once` to include essential files only once, ensuring critical files are not included
multiple times and stopping the script if they are missing.

You might also like