PHP Arrays & Loops Tutorial

Ghost

Seasoned Veteran
Blogger
Jun 25, 2009
3,200
186
213
Earth
wubur.com
FP$
2,492
PHP, like many other languages, uses arrays to store information. Arrays can help keep data organized, easily retrievable, and even be translated to/from other languages (such as JavaScript) to let PHP play around with user information that someone submitted in a form. There are lots of different things we can do with arrays, but today we'll simply discuss what they are, how to create one, and how to "loop" through them. I'll show you an example that demonstrates why looping is an important skill to know in PHP or any other language.

If you want to learn some basic PHP, you can check out my Beginner PHP Tutorial which covers how to create / start a PHP file, declare variables, analyze the variables (with if/else statements), show information on the page, and combine strings of information together. We'll do a bit of all of that here, so make sure you have read that tutorial first.

This tutorial will be repetitive to help you understand arrays and looping. Enjoy!

tutorial.php
Code:
<?php
$data = array(); 
// we have started an empty array 

$info = array("name"=>"Ghost", "age"=>25);
// we have started an array with a name and age value 
?>
In this example we have two arrays. One of them is empty, and one of them is storing my current age and username. As you can see, starting an array is as easy as having your variable (such as $data), and then using the syntax array();
Inside of the array, you can do a variety of things. First we'll take a look at our $info array, which is an associative array.


tutorial.php
Code:
<?php
$data = array();  // empty array 

$info = array("name"=>"Ghost", "age"=>25); // associative array
echo $info["name"]; // echo out the name value from our array 
$myage = $info["age"]; // set our age value to a variable 
?>
In this example we did two things. First, we echo'd out my name on to the page. If we opened up our PHP page it would literally only say "Ghost" on the page. The age isn't being echo'd out so, it would not show up.

The reason I made the $myage variable was to show you that an array value can be assigned to a variable. This can be very useful for large arrays to avoid your script having to read through a large array to get to a piece of information. For example, if an array has 100 different pieces of data inside of it, it can be very beneficial to declare a variable for a piece of information like I did with $myage if you plan on using the value a lot later on.

Associative arrays essentially "associate" a named key with a value.
A key is what you see in the [] portion of the array retrieval. For example in $info["name"], the key is "name". In the next example, our key will actually be a number instead of a string.

tutorial.php
Code:
<?php
$data = array();  // empty array 
$info = array("name"=>"Ghost", "age"=>25, "role"=>2); // associative array

$groups = array(0=>"User", 1=>"Moderator", 2=>"Administrator); 
// This is a numeric array. 

// Let's use string concatenation from the Beginner PHP Tutorial to show some sentences:
echo $groups[0] . " is Role 0 <br />";
echo $groups[1] . " is Role 1 <br />";
echo $groups[0] . " is Role 2 <br />";
?>
So, a numeric array goes up by 1 each time a new value is added to the array. We can set up the array like I did, or we can add a value to the array quite simply. Check this out:

tutorial.php
Code:
<?php
$data = array();  // empty array 
$info = array("name"=>"Ghost", "age"=>25,  "role"=>2); // associative array

$groups = array();
// This is an empty array. 

$groups[] = "User"; 
$groups[] = "Moderator"; 
$groups[] = "Administrator"; 

$role = $info["role"];
echo "{$info["name"]} is a Company {$groups[$role]}."; 
?>
In this latest example, we are using the role=2 information in the $info array to find the role name in our $groups array. We also are adding the roles to our $groups array differently than before. When you use $arrayName[] , you are telling PHP that whatever comes after the equals sign should be added to that array.

So when we use $groups[] = "User" first, then groups looks like this:
Code:
$groups = array(0=>"User");
Then we obviously added Moderator and Administrator in too.
You also may have noticed that we used { and } around our variables / array references in our sentence. This is a way to make sure that quotations and syntax don't break our string value inside the original "double quotes". It's similar to just using a variable inside a string, but is additional syntax that doesn't change the value of our actual variable - just lets PHP read it without any issues.

In our example above our tutorial page now shows:
"Ghost is a Company Administrator."

So, now that you know how to set up an associative ($info) array, numeric ($groups) array, and an empty array that we can add values to ($array[] = $newvalue), it's time to learn about one more thing... multidimensional arrays.

Multidimensional arrays are arrays with arrays inside of them.
Let's take a look:

tutorial.php
Code:
<?php
$data = array();  // empty array 
$info = array("name"=>"Ghost", "age"=>25,  "role"=>2, "friends"=>array("Frank", "James", "Chris")); // associative array

$groups = array("User", "Moderator", "Administrator");
/* 
Yes, numeric arrays do not require you to include the #=> syntax in front of each value
You can just list the values inside the array, and PHP will automatically apply 0, 1, 2 keys to our User, Moderator, and Administrator values 
*/ 

$role = $info["role"];
echo "{$info["name"]} is a Company {$groups[$role]}."; 
?>
This prints out "Ghost is a Company Administrator." on the page.

As you can see, I did a few new things. I didn't use the numeric keys in the $groups array because PHP figures them out by default, and I also used the $role name in a sentence. I did this because $role = 2, from the $info array, and $groups[2]= the group name (Administrator). Remember, even though we did not supply the numeric keys, PHP automatically made $groups[0] = "User", 1 = Moderator, and 2 = Administrator.

However, the most important thing I did was include an array inside of the array. Our "friends" key in the $info array makes our $info array not only be associative, but a multidimensional array. Also, you may have noticed that the $info["friends"] which is its own array is a numerical array.

If we wanted to know the first friend of this user, we could do...
Code:
echo $info["friends"][0];
This would print out "Frank" on the page because that's key 0 of the friends array - the first result.

Now let's loop through our array.
We love loops because they are perfect for repetitive functions. Instead of running duplicate code for each item in the array, a loop will find all the different values inside of the array & do things with it. We'll loop through our friends array to do things with each.

tutorial.php
Code:
<?php
$data = array();  // empty array 
$info = array("name"=>"Ghost", "age"=>25, "role"=>2, "friends"=>array("Frank", "James", "Chris")); // associative array

$groups = array("User", "Moderator", "Administrator");
/* 
Yes, numeric arrays do not require you to include the #=> syntax in front of each value
You can just list the values inside the array, and PHP will automatically apply 0, 1, 2 keys to our User, Moderator, and Administrator values 
*/ 

$role = $info["role"];
echo "{$info["name"]} is a Company {$groups[$role]}. <br />"; 

// FOREACH LOOP
foreach($info["friends"] as $friend){
echo $friend . " is friends with {$info["name"]}. <br />";
}
?>
In this example we see the following printed out on the page:
Ghost is a Company Administrator.
Frank is friends with Ghost.
James is friends with Ghost.
Chris is friends with Ghost.

This is because we used a foreach loop to do the same thing with each array value. We're saying "for each name in the friends array... do something". Additionally, the syntax is quite simple with foreach($array as $variable) being easy to remember.

We could also change foreach to show some array keys/labels for our values like this... This adds an extra piece to our foreach statement by breaking up the array KEY and VALUE. That way we can access the key # or name, and the value separately. It is useful if you need to do something like "if KEY == this, do something different". An example of this would be if you wanted to echo out everything except one array value, but generally speaking you will mostly use loops when you want to do the same thing with each value. You normally will not loop through multiple array values if they all require separate logic depending on the key, but there are times when you may need to.

Code:
foreach($info as $key => $value){
echo "$key ";
}
This would print out...
"name age role friends", because those are the key names in our array. So because we separate the key and value into separate variables in our foreach, we can access both the key name and the value itself.

Consider the following...
Code:
<?php
$arr = array("key1"=>"value1", "key2"=>"value2");
foreach($arr as $key => $value){
echo "The $key is $value <br />";
}
?>
This shows:
The key1 is value1
The key2 is value2

We can also loop through an array with a "for loop". It's my favorite type of loop, but is a little bit more complicated. I like for loops because they are very efficient & fast, but foreach can be good too. In fact, I used foreach first and I think it's a good loop to learn at first because it's easy to remember.

We need to know the amount of values inside of the array.

tutorial.php
Code:
<?php
$data = array();  // empty array 
$info = array("name"=>"Ghost", "age"=>25, "role"=>2, "friends"=>array("Frank", "James", "Chris")); // associative array

$groups = array("User", "Moderator", "Administrator");

$role = $info["role"];
echo "{$info["name"]} is a Company {$groups[$role]}, and is {$info["age"]} years old. <br />"; 

$num = count($info["friends"]); // count the number of values in the info=> friends array
for($x = 0; $x < $num; $x++){
echo $info["friends"][$x] . " is friends with {$info["name"]}. <br />";
}
?>
In this example we see the following printed out on the page:
Ghost is a Company Administrator, and is 25 years old.
Frank is friends with Ghost.
James is friends with Ghost.
Chris is friends with Ghost.

Let's break down the for loop.
We start by getting the value of $num. It's the number of friends, which is 3.
Then we start our for loop with a new variable we named $x.
$x = 0.
Then we say $x < $num. This means that our for loop will start with $x equaling 0, and it will loop for as long as $x remains less than ( < ) $num or in other words, for as long as $x is less than 3.

Then we use $x++;
This tells our for loop that each time the loop runs, we want to increment $x by 1. When you have a number stored in a variable, using $variable++ is the same as saying $variable = $variable + 1. It just adds 1 to itself.

So in our for loop, $x starts at 0. Every time the loop runs, it goes up by 1, and it will keep looping for as long as $x is less than $num (3). So in this case, the first loop $x = 0, the second $x = 1, and the third $x = 2. After our first 3 loops, $x would become equal to 3, and the looping stops because our rules say that the loop should only run if $x is LESS THAN 3 - not equal to it.


In each our loops, we access the friends name with:
$info["friends"][$x]

So, our 3 loops are accessing the friend's name like this:
$info["friends"][0]
$info["friends"][1]
$info["friends"][2]

Because 0, 1, 2 are the values of our $x variable for our 3 loops
0 refers to the first friend in our $info["friends"] array, 1 refers to the second friend, and 2 refers to the third friend (because remember, arrays start at 0 by default for the keys)


You may be wondering why we use loops. Well, loops are perfect for when the amount of information can vary in amount. If everyone only ever has one age and name, we don't need to loop through the information. However, for things like friends where people could have 0 friends, 3 friends, or even hundreds of friends, loops let us execute code for each value in the array regardless of the amount. They can even double up on each other - a loop within a loop. This could be taken further to have dozens of nested loops, but there are very few cases when that would be required. Loops are good, but can definitely get out of control.

For large amounts of data it's important that you are not causing your script/page to load forever due to a large loop. An example of this would be a forum with 1 million posts in a category. Instead of looping through all 1 million pieces of content, we would instead fetch the first 25-100 results and loop through those. We would move on to the other content if the user went to page 2, for example. Loops are only as good as the programmer, so make sure you are not running unnecessary loops on big data unless you truly have to.

So let's take a look at one final example of our for loop, with some arrays.

tutorial.php
Code:
<?php
$data = array();  // empty array 
$info = array("name"=>"Ghost", "age"=>25, "friends"=>array(array("name"=>"Frank", "age"=>23), array("name"=>"Chris", "age"=>26), array("name"=>"James", "age"=>27));

$num = count($info["friends"]); // count the number of values in the info=> friends array
for($x = 0; $x < $num; $x++){ // loop through all the friends results
 // in this example, our friends array actually holds a bunch of separate arrays! 

 if($info["friends"][$x]["age"] > $info["age"]){ // if our friend's age is older than ours
  $data[] = $info["friends"][$x]; // add this friend to the data array
 }

} // end of for loop 

print_r($data);
?>
In this last example we are really bringing everything together.
We start with an empty array, $data.
We also have our $info array which stores our name, age, and our friends. The friends array holds multiple arrays, which all have information about the friend. When we loop through the friends array, we can access each friend's information by using the proper array key (name or age). In this example we are trying to find all of the friends who are older than us. We correctly discover that Chris & James are older than us, so they are added to the $data array.

The result would be the same as creating the $data array like this:
Code:
<?php
$data = array(array("name"=>"Chris", "age"=>26), array("name"=>"James", "age"=>27));
?>
So, as you can see you can access data in the array with the loop, analyze it, and then do things with that information such as constructing the separate $data array to hold only our friends who are older. This is obviously a very specific example, but so much more can be done including echoing values on to the page, triggering another script to run, or really anything you can imagine.
 
  • Like
Reactions: Malcolmjr96