The last time I wrote about understanding PHP Arrays, today we are going to be looking at how arrays work with loops in PHP.
I choose to dwell on this array topic and to simplify it as much as I can because I really had a hard time getting my head around this topic when I was starting out my journey as a web developer with PHP, if you are in that position right now you don't have to be scared you are in the right place, so let's get straight to it.
PHP as a programming language has different array functions that can help one iterate through his/her array of data.
We are going to carefully examine these loops and how you can use them with arrays
One of the most important aspects of a programming language that works interchangeably with arrays is loop. Loops are used to execute the same block of code again and again, as long as a certain condition is true.
Loops in PHP
- for loops
- foreach loops
- while loops
- do...while loops
Note: loops can be used for so many things when you are creating an application but the aim of loops in this article is to explain how they work interchangeably with arrays. For beginners
for loop
To display the use of array with for loop, let's create an array variable and populate it with some content
$arr = ['a', 'b','c', 'd', 'e', ]; //array variable
//skeleton of a for loop block
for ($i=0; $i <= 10 ; $i++) {
# code...
}
Now we have created an array variable and we also created a for loop
skeleton, let me explain that block of code above especially the for loop
block.
The $i = 0;
is a variable initializer: this means that for us to use the $i
variable we need to make it usable by assigning a zero value to it.
The second segment of the expression is the condition segment. This segment states the condition which the loop will follow in iterating so that it won't run into an infinite loop(unending iteration), in our case we are telling the loop to keep running a certain block of code if the value of $i
remains less than 10
, and once the value of $i
equals 10
stop the loop!
The last segment of the for loop
block is the iteration pattern, this segment defines the iteration pattern depending on how you structure your logic. Let's add our $arr
variable to the mix.
We are going to be introducing an important array function called count()
.
count()
is a PHP function that returns the length of your array: by length I mean the total number of items contained in array data.
$arr = ['a', 'b','c', 'd', 'e']; //array variable
$countArr = count($arr); //this returns length of the array
for ($i =0; $i <= $countArr ; $i++) {
echo 'iteration '. $i;
}
#results to
// iteration 0
// iteration 1
// iteration 2
// iteration 3
// iteration 4
Our code executed successfully and with the help of our array length we are able to condition our for loop
to iterate according to the length of our array.
Notice that the $arr
does not have many affiliations with the for loop
as a matter of fact you can successfully condition a for loop
without the $arr
, that is why in a real world scenario you don't have much to do with for loop
when it comes to arrays in PHP.
foreach loops
foreach loop
is the most important loop specifically made for arrays in almost all programming language. foreach loop
iterate through different types of array and helps one access individual value of the giving array data inside the foreach loop
code block.
foreach ($array as $value) {
// code to be executed;
}
I am going to be giving examples of using array with foreach loop
, first let's see how to loop through an indexed array with a foreach loop
. if you don't know what an index array is you can check out my article on Understanding PHP Arrays
### create a an array variable
$arr = ['red', 'blue', 'green'];
// lets loop
foreach($arr as $item){
echo 'the color is '. $item .'<br>';
}
## results to
// the color is red
// the color is blue
// the color is green
One beautiful thing about foreach loop
is that you can access the individual item of the array inside the loop and its very flexible unlike the for loop
which doesn't permit such unless you use the counter variable as the array index inside the loop which i will show you in a second.
Let's look at another example with an associative array.
### create a an array variable
$person= ['name' => 'Victor', 'age' => '23', 'country' => 'Nigeria' ];
// lets loop
foreach($person as $data){
echo $item .' <br>';
}
## results to
// Victor
// 23
// Nigeria
//////
Another important feature of a foreach loop
is the ability to access the index(key) of the array in iteration.
Let's take a look at another example
// lets loop
$person= ['name' => 'Victor', 'age' => '23', 'country' => 'Nigeria' ];
foreach($person as $key => $data){
echo $key. ' : '. $data. '<br>';
}
## results to
// name: Victor
// age: 23
// country: Nigeria
## To achieve this kind of result in any other array type requires a little tweak with the counter variable or the initializer variable.
// Let's use the for loop for example
$arr = ['a', 'b','c', 'd', 'e']; //array variable
$countArr = count($arr); //this returns length of the array
for ($i =0; $i <= $countArr ; $i++) {
echo $arr[$i] . '<br>' ;
}
#results to
// a
// b
// c
// d
// e
Note the $key variable is only functional when looping through an associative array. it doesn't work with an indexed array
All other types of loop like the while loop
and the do..while loop
and the for loop
follow the same pattern which is basically to iterate over a block of code once a certain condition is met.
while loop
while loop executes some block of code when a certain condition is met, therefore the code inside the while loop
code block cannot run unless the condition is passed.
Here are the few things you need to know about while loops:
The variable initializer is declared outside the loop statement unlike the for loop
whose variable initializer is declared inside the loop statement
//synthax of a while loop
while (condition is true) {
//code to be executed;
}
// example of a while loop
$x = 0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
### while loop with arrays
$arr = ['a', 'b','c', 'd', 'e', ]; //array variable
$countArr = count($arr);
$x = 0;
while($x <= $countArr) {
echo $arr[$x] <br>";
$x++;
}$initiated outside the code bblock
do..while loop
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.
Just Like a while loop
the variable initializer of a do..while loop
is also initiated outside the loop statement/code block
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
Important point to take note of
foreach loop
is the only loop that is specially built for arrays in PHP (my opinion though)- The $key variable is only functional when looping through an associative array. it doesn't work with an indexed array!
- In the real world scenario you will barely need the
do..while loop
- In a real world application you won't be needing the
for loop
anddo..while
when working with arrays, occasionally there might be reasons to use thewhile loop
but it's rare because personally I have never used awhile loop
for an array but I no there might be situations where it might be needed. if you know of such situationslet me know in the comment section.
Thanks for reading, I hope you learned something, let me know how you feel about this article in the comment section