PHP Unit 2
PHP Unit 2
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.
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
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
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:
Examples
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
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.
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;
Continue Example
<?php
$x = 0;
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 has over 1000 built-in functions that can be called directly from within a
script to perform a specific task in PHP Functions.
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.
function function_name()
//Statement to be executed
Code:
<!DOCTYPE html>
<html>
<body>
<?php
functionwelcMsg()
}
welcMsg();
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
functionwelcMsg()
welcMsg();
?>
</body>
</html>
Explanation:
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;
?>
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.
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.
function factorial($n)
if ($n == 1) {
return 1;
} else {
echo factorial(5);
// Output: 120
PHP Arrays
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?
An array can hold many values under a single name, and you can access the values
by referring to an index number.
array();
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);
?>
Associative arrays are arrays that use named keys that you assign to them.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
PHP - Multidimensional 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.
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>";
?>
In this chapter, we will go through the following PHP array sort functions:
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);
?>
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);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
<?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).
Syntax
array_merge(array1, array2, array3, ...)
Parameter Values
Parameter Description
Example
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
Example
<?php
$a=array(3=>"red",4=>"green");
print_r(array_merge($a));
?>