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 PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Example
Print $i as long as $i is less than 6:
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if the
condition is still true.
The break Statement
With the break statement we can stop the loop even if the condition is still true:
Example
Stop the loop when $i is 3:
$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
}
OUTPUT: 12
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $i is 3:
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;
while ($i < 6) {
$i++;
if ($i == 3) continue;
echo $i;
}
?>
</body>
</html>
OUTPUT: 1245
Example
Count to 100 by tens:
$i = 0;
while ($i < 100) {
$i+=10;
echo $i "<br>";
}
The PHP do...while Loop
The do...while loop will always execute the block of code at least once, it will then check the
condition, and repeat the loop while the specified condition is true.
Example
Print $i as long as $i is less than 6:
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
The PHP for Loop
The for loop is used when you know how many times the script should run.
Syntax
for (expression1, expression2, expression3) {
// code block
}
This is how it works:
expression1 is evaluated once
expression2 is evaluated before each iteration
expression3 is evaluated after each iteration
Example
Print the numbers from 0 to 10:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
What is an Array?
An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name.
PHP Array Types
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
Array Items
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.
You can have different data types in the same array.
Example
Array items of four different data types:
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);
Indexed Arrays: These arrays use numeric indices. You can create an indexed array
like this:
$fruits = array("Apple", "Banana", "Cherry");
Associative Arrays: These arrays use named keys that you assign to them. They are
useful when you want to associate values with specific keys.
$ages = array("Alice" => 25, "Bob" => 30, "Charlie" => 35);
Multidimensional Arrays: These are arrays that contain one or more arrays. You
can think of them as arrays of arrays. They are often used to store data in a tabular format.
$contacts = array(
"John" => array("phone" => "123-4567", "email" => "[email protected]"),
"Jane" => array("phone" => "987-6543", "email" => "[email protected]")
);
STRING
A string is a sequence of characters, Strings in PHP are surrounded by either double quotation
marks, or single quotation marks.
Example
echo "Hello";
echo 'Hello';
String Length
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":
echo strlen("Hello world!");
Word Count
The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":
echo str_word_count("Hello world!");
Search For Text Within a String
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match
is found, it will return FALSE.
Example
Search for the text "world" in the string "Hello world!":
echo strpos("Hello world!", "world");
PHP - Modify Strings
PHP has a set of built-in functions that you can use to modify strings.
1. Upper Case
Example
The strtoupper() function returns the string in upper case:
$x = "Hello World!";
echo strtoupper($x);
2. Lower Case
Example
The strtolower() function returns the string in lower case:
$x = "Hello World!";
echo strtolower($x);
3. Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello World!":
$x = "Hello World!";
echo strrev($x);
4. String Concatenation
To concatenate, or combine, two strings you can use the . operator:
Example
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
You can add a space character like this:
Example
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;