0% found this document useful (0 votes)
14 views20 pages

PHP Unit 2

Uploaded by

bedkesachin1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
14 views20 pages

PHP Unit 2

Uploaded by

bedkesachin1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

PHP Loops

Often when you write code, you want the same block of code to run over and over
again a certain number of times. So, instead of adding several almost equal code-
lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a
certain condition is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is


true
 do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The following chapters will explain and give examples of each loop type.

While Loop
The while loop - Loops through a block of code as long as the specified condition
is true.

The while loop executes a block of code as long as the specified condition is true.

Syntax
while (condition is true)

{
code to be executed;
}

Examples

The example below displays the numbers from 1 to 5:


Example
<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

Example Explained

 $x = 1; - Initialize the loop counter ($x), and set the start value to 1
 $x <= 5 - Continue the loop as long as $x is less than or equal to 5
 $x++; - Increase the loop counter value by 1 for each iteration

This example counts to 100 by tens:

PHP do while Loop

The do...while loop - Loops through a block of code once, and then repeats the
loop as long as the specified condition is true.

The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);

Examples

The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop
will write some output, and then increment the variable $x with 1. Then the
condition is checked (is $x less than, or equal to 5?), and the loop will continue to
run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

Note: In a do...while loop the condition is tested AFTER executing the statements
within the loop. This means that the do...while loop will execute its statements at
least once, even if the condition is false.

For Loop

The for loop - Loops through a block of code a specified number of times.

The for loop is used when you know in advance how many times the script should
run.

Syntax
for (init counter; test counter; increment counter)

{
code to be executed for each iteration;
}

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the
loop continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

Examples

The example below displays the numbers from 0 to 10:


Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

Example Explained

 $x = 0; - Initialize the loop counter ($x), and set the start value to 0
 $x <= 10; - Continue the loop as long as $x is less than or equal to 10
 $x++ - Increase the loop counter value by 1 for each iteration

This example counts to 100 by tens:

PHP Break

You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>

PHP Continue

The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
This example skips the value of 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

Break Example
<?php
$x = 0;

while($x < 10) {


if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
?>

Continue Example
<?php
$x = 0;

while($x < 10) {


if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x <br>";
$x++;
}
?>

Functions in PHP

A function is a piece of code that takes another input in the form of a parameter,
processes it, and then returns a value.

A PHP Function feature is a piece of code that can be used over and over again and
accepts argument lists as input, and returns a value.

PHP comes with thousands of built-in features.

Built-in Functions in PHP

PHP has over 1000 built-in functions that can be called directly from within a
script to perform a specific task in PHP Functions.

User Defined Functions in PHP

 In PHP, functions can be written on their own in addition to the built-in PHP
functions.
 A function is a set of statements that can be used repeatedly in a program.
 When a page loads, a feature will not run automatically.
 A call to a function will cause it to be executed.

Advantages of PHP Function

 Reusability of Code: Unlike other programming languages, PHP Functions are


specified only once and can be called multiple times.
 Less Code: It saves a lot of code because the logic doesn't have to be written
several times. You can write the logic only once and reuse it by using functions.
 Simple to Comprehend: The programming logic is separated using PHP
Functions. Since every logic is divided into functions, it is easier to understand
the application's flow.

Creating and Calling Function


In PHP, the function name is any name that ends in an open and closed parenthesis.

 The keyword function is often used to start a function name.


 To invoke a function, simply type its name followed by the parenthesis.
 A number cannot be the first character in a feature name. It can begin with a
letter or an underscore.
 The case of a feature name is unimportant.
Syntax:

function function_name()

//Statement to be executed

Code:

<!DOCTYPE html>

<html>

<body>

<?php

functionwelcMsg()

echo "Hello welcome!";

}
welcMsg();

?>

</body>

</html>

<!DOCTYPE html>

<html>

<body>

<?php

functionwelcMsg()

echo "Hello welcome!";

welcMsg();

?>

</body>

</html>

Explanation:

In the above example, a function called "welcMsg()" is created. The beginning of


the function code is indicated by the opening curly bracket {, and the end of the
function is indicated by the closing curly bracket }. The function says "Hello
welcome!"; write the function's name in brackets () to invoke it.
Output:

PHP Functions - Returning Value

This means the PHP Function can be called by its name, and when executing the
function, it will return some value.

Example:

<?php

function circle($r){

return 3.14*$r*$r;

echo "Area of circle is: ".circle(3);

?>

Output:
Recursive Functions in PHP

Recursive functions are a powerful and useful feature in PHP that allows a function
to call itself repeatedly until a certain condition is met.

This technique can be especially useful when dealing with problems that require
repetitive computations or operations, such as traversing nested data structures,
sorting or searching algorithms, and mathematical calculations.

At its core, recursion involves breaking down a complex problem into smaller,
more manageable sub-problems that can be solved recursively.

Each recursive function call works on a smaller subset of the problem until the
base case is reached, at which point the function begins to return values and
unwind the call stack.

Recursive functions can be more elegant and efficient than iterative approaches in
some cases, especially when dealing with large or complex data structures.

However, iterative approaches may be more appropriate in situations where


memory usage is a concern or when the problem can be solved more efficiently
using a non-recursive algorithm.

When using recursive functions in PHP, it is important to carefully design the


function to ensure that it terminates correctly and does not consume too many
resources.

This means defining an appropriate base case that will eventually be reached, and
ensuring that each recursive call works on a smaller subset of the problem until the
base case is reached.

PHP provides a built-in mechanism to limit the depth of recursive function calls
using the debug.max_nesting_level configuration setting.

This can help prevent infinite loops or excessive resource usage caused by
recursive functions that do not terminate properly.

However, it is important to use this setting judiciously and to ensure that the
recursion depth limit is appropriate for the specific problem being solved.
Recursive functions are a powerful tool in PHP that can simplify complex
problems by breaking them down into smaller sub-problems.

However, they must be used with care and attention to detail to ensure that they
terminate correctly and do not consume excessive resources.

By understanding how recursion works and when it is appropriate to use, PHP


developers can add a powerful technique to their problem-solving toolbox.

Generate Factorial of a Number Using Recursive Function in PHP.

Here's an example of how to generate the factorial of a number using a recursive


function in PHP:

function factorial($n)

if ($n == 1) {

return 1;

} else {

return $n * factorial($n - 1);

echo factorial(5);

// Output: 120
PHP Arrays

An array stores multiple values in one single variable:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values
by referring to an index number.

Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
Get The Length of an Array - The count() Function

The count() function is used to return the length (the number of elements) of an
array:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

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

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
PHP - Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels
deep. However, arrays more than three levels deep are hard to manage for most
people.

The dimension of an array indicates the number of indices you need to select
an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array


of arrays of arrays).

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15
First, take a look at the following table:

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two indices:
row and column.

To get access to the elements of the $cars array we must point to the two indices
(row and column):

Example

<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key
Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending
alphabetical order:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

The following example sorts the elements of the $numbers array in ascending
numerical order:

Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>

Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending
alphabetical order:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>

Sort Array (Ascending Order), According to Value - asort()

The following example sorts an associative array in ascending order, according to


the value:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

Sort Array (Ascending Order), According to Key - ksort()

The following example sorts an associative array in ascending order, according to


the key:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

Sort Array (Descending Order), According to Value - arsort()

The following example sorts an associative array in descending order, according to


the value:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>

Sort Array (Descending Order), According to Key - krsort()

The following example sorts an associative array in descending order, according to


the key:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

Merge two arrays into one array:

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>

Merging Arrays

The array_merge() function merges one or more arrays into one array.

Tip: You can assign one array to the function, or as many as you like.
Note: If two or more array elements have the same key, the last one overrides the
others.

Note: If you assign only one array to the array_merge() function, and the keys are
integers, the function returns a new array with integer keys starting at 0 and
increases by 1 for each value (See example below).

Tip: The difference between this function and


the array_merge_recursive() function is when two or more array elements have the
same key. Instead of override the keys, the array_merge_recursive() function
makes the value as an array.

Syntax
array_merge(array1, array2, array3, ...)
Parameter Values

Parameter Description

array1 Required. Specifies an array

array2 Optional. Specifies an array

array3,... Optional. Specifies an array

Example

Merge two associative arrays into one array:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>

Example

Using only one array parameter with integer keys:

<?php
$a=array(3=>"red",4=>"green");
print_r(array_merge($a));
?>

You might also like