Lesson 12 - Arrays and loops in PHP

PHP Basic constructs Arrays and loops in PHP

In the previous lesson, For and while loops in PHP, we went over how to use for and while loops in PHP. In today's lesson, we're going to finish up with loops and show you how to use them properly when working with arrays.

Filling an array using loops

Loops are widely used for automatizing array manipulations. Usually, there are lots of items in an array and dealing with them one by one would certainly not be a good idea. Let's start by filling an array with numbers from 1 to 100.

We know the number of loop iterations, 100, so we will use the for loop. Its control variable ($i) will go from 0 to 99 (an array of 100 items will have indexes from 0 - 99). We'll have to increase the value by 1 because we want values from 1 to 100:

$numbers = array();
for ($i = 0; $i < 100; $i++)
        $numbers[$i] = $i + 1;

Printing an array using loops

We now have an array filled with 100 numbers. However, we don't usually generate arrays like this. In most cases, we retrieve values from databases. Regardless, the approach shown above will do for now :) Another common thing to do is print values from an array into a table.

The for loop

I'm pretty sure you could have come up with the following code at this point if you were given the task:

echo('<table border="1"><tr>');
for ($i = 0; $i < 100; $i++)
        echo('<td>' . htmlspecialchars($numbers[$i]) . '</td>');
echo('</tr></table>');

The code prints the contents of the array into a table using the for loop. In real applications, there would most likely be other kinds of content in the array such as comments from a database, which we will get to soon enough.

The foreach loop

As a matter of fact, there is a shorter and more sophisticated way to print arrays, the foreach loop. Its usage is as follows:

foreach ($collection as $element)

Foreach iterates over array items and stores the current item in a variable. This is the difference between foreach and for loops, which store the item's index, not the item itself.

Here's how we would print the array into a table using foreach:

echo('<table border="1"><tr>');
foreach($numbers as $number)
        echo('<td>' . htmlspecialchars($number) . '</td>');
echo('</tr></table>');

The program's output will be identical. Foreach is mostly used for reading and working with objects, which we will get to later as well because it is way more readable than for loops.

The loop's variable in the example above contains a copy of the element at a given position. If we tried to modify the variable $number, it wouldn't affect the array at all because all we'd be doing is modifying a copy of the current element and not the element itself. On the other hand, if we wanted to multiply every single element by 2, using a for loop be relatively easier:

for ($i = 0; $i < 100; $i++)
        $numbers[$i] = $numbers[$i] * 2;

Either way, we don't want to modify the original array, so we'll use foreach for these intents and purposes.

PHP array functions

PHP provides a wide range of functions for working with arrays. We won't go into them in detail, we'll just show you a list of the most important ones. Each function references the corresponding page in the official PHP manual where it is described and shown in examples. Every time we program something in PHP, it's a good idea to check whether a function for what we need already exists. Doing so will save us time and prevent us from making mistakes. Internal PHP functions are written in the C language, so they're way faster than anything we could come up with.

You don't absolutely have to examine these functions in detail, just read what they do and look them up later when you need them.

array_fill Fills an array with values
array_flip Exchanges all keys with their values.
array_intersecĀ­t_key Computes array intersections using keys for comparison.
array_intersect Computes array intersections.
array_keys Returns all of the keys or a subset of the keys in a given array.
array_map Applies a callback to the elements of a given array.
array_merge Merges one or more arrays.
array_pop Pops the element off the end of an array.
array_push Pushes one or more elements onto the end of an array.
array_reverse Returns an array with its elements ordered backward.
array_search Searches the array for a given value and returns the corresponding key if successful.
array_shift Shifts an element off the beginning of an array.
array_sum Calculates the sum of values in an array.
array_unique Removes duplicate values from an array.
array_unshift Prepends one or more elements to the beginning of an array.
array_values Returns all the values of an array.
count Counts all elements in an array or things in an object.
extract Establishes a variable for each array key and assigns the corresponding value to it.
ksort Sorts an array by keys.
sort Sorts an array by values.

Array of arrays

Have you ever wondered whether we could put an entire array into another? Arrays are an ordinary data type, so we can absolutely insert arrays one into another. We'll work with arrays like these very often:

$paul = array(
        'name' => 'Paul Smith',
        'age' => '20',
);
$thomas = array(
        'name' => 'Thomas Doe',
        'age' => '50',
);
$jane = array(
        'name' => 'Jane Doe',
        'age' => '35',
);
$people = array($paul, $thomas, $jane);

We created 3 arrays and stored them into another at the very end. The first couple of arrays represent people, the outer array keeps them together so we can work with them easily.

The same exact array would be returned by a database request for users. Except the first and last names would probably be separate values. With all that you know, you should be able to print it out without any help. Just to be sure, we'll do it together:

echo('<table border="1">');
echo('<tr><th>Name</th><th>Age</th></tr>');
foreach ($people as $person)
{
        echo('<tr><td>' . htmlspecialchars($person['name']) . '</td>');
        echo('<td>' . htmlspecialchars($person['age']) . '</td></tr>');
}
echo('</table>');

Your page
localhost

We often call this type of array multidimensional, mainly when the items stored are numbers. Such an array can be imagined as a table (or matrix). Here is an example of a 3x3 array:

$matrix = array(
        array(1, 2, 3),
        array(4, 5, 6),
        array(7, 8, 9)
);

Of course, we'd use loops to generate large arrays like that. Maybe even use nested for loops to print them our, like we did with our simple multiplication table. Let's go over the code for printing the array we set up above:

echo('<table border="1">');
for ($j = 0; $j < 3; $j++)
{
        echo('<tr>');
        for ($i = 0; $i < 3; $i++)
        {
                echo('<td>' . $matrix[$j][$i] . '</td>');
        }
        echo('</tr>');
}
echo('</table>');

The result:

Your page
localhost

I used a 2D array to program the on-line sudoku solver, so I'm sure you'll find them rather useful. In the next lesson, String functions in PHP, we're going to finish up with the crucial, basic aspects of PHP. We'll talk about string functions and learn how to declare our own functions. Today's examples are, as always, available for download below.


 

Download

Downloaded 25x (1.67 kB)
Application includes source codes in language PHP

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
For and while loops in PHP
Thumbnail
All articles in this section
PHP basic constructs
Activities (11)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!