PHP Tutorial Arrays & Loops | Promotion Forum

PHP, like many other languages, uses matrices to store information. Arrays can help keep data organized, easily retrievable and even translated into / from other languages ​​(such as JavaScript) to allow PHP to play with the user information that someone sent in a form. There are many different things we can do with the arrangements, but today we will simply discuss what they are, how to create one and how to "cycle" through them. I will show you an example that shows why the loop is an important skill that you should know in PHP or in any other language.

If you want to learn some basic PHP, you can check my PHP Tutorial for beginners that explains how to create / start a PHP file, declare variables, analyze variables (with if / else statements), display information on the page and combine strings of information together. Here we'll do a little bit of all that, so make sure you've read that tutorial first.

This tutorial will be repetitive to help you understand the matrices and loops. Enjoy!

tutorial.php

Code:

"Ghost", "age" => 25);
// we have started a matrix with a name and age value
?>

In this example we have two matrices. One of them is empty, and one of them is storing my current age and my username. As you can see, starting a matrix is ​​as easy as having its variable (like $ data) and then using the syntax training();
Within the matrix, you can do a variety of things. First we will take a look at our $ info matrix, which is a associative matrix.

tutorial.php

Code:

"Ghost", "age" => 25); // associative matrix
echo $ info["name"]; // echo the value of the name of our matrix
$ myage = $ info["age"]; // set our age value to a variable
?>

In this example we did two things. First, we echoed my name on the page. If we opened our PHP page, I would literally just say "Ghost" on the page. Age is not echoing, so it would not appear.

The reason why I made the variable $ myage was to show you that you can assign a value of matrix to a variable. This can be very useful for large arrays to prevent your script from having to read through a large array to get information. For example, if a matrix has 100 different data within it, it can be very beneficial to declare a variable for information like the one I made with $ myage if you plan to use the value much later.

Associative matrices essentially "associate" a name key with a value.
A key is what you see in the [] part of the recovery of the matrix. For example in $ info[“name”], the key is "name". In the following example, our key will be a number instead of a string.

tutorial.php

Code:

"Phantom", "age" => 25, "role" => 2); // associative matrix

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

// Let's use the string concatenation of the PHP tutorial for beginners to show some sentences:
echo $ groups[0] . "It's the paper 0 
"; echo $ groups[1] . "is the role 1
"; echo $ groups[0] . "It's paper 2
"; ?>

Therefore, a number matrix increases by 1 each time a new value is added to the matrix. We can configure the matrix as I did, or we can add a value to the matrix quite simply. Watch this:

tutorial.php

Code:

"Phantom", "age" => 25, "role" => 2); // associative matrix

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

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

$ role = $ info["role"];
echo "{$ info["name"]} is a company {$ groups[$role]} ";
?>

In this last example, we are using the information of role = 2 in the $ info matrix to find the name of the function in our matrix $ groups. We are also adding the roles to our $ groups array in a different way than before. When you use $ arrayName[] , is telling PHP that everything that comes after the equal sign must be added to that matrix.

So when we use $ groups[] = "User" first, then the groups look like this:

Code:

$ groups = array (0 => "User");

So obviously we add Moderator and Administrator too.
You may also have noticed that we use { Y } Around our variables / matrix references in our sentence. This is a way to make sure that quotes and syntax do not break our string value within the original "double quotes". It is similar to just using a variable within a string, but it is an additional syntax that does not change the value of our real variable, it only allows PHP to read it without any problem.

In our previous example, our tutorials page now shows:
"Ghost is an administrator of the company."

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

Multidimensional matrices are matrices with matrices inside them.
We'll see:

tutorial.php

Code:

"Ghost", "age" => 25, "role" => 2, "friends" => array ("Frank", "James", "Chris")); // associative matrix

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

$ role = $ info["role"];
echo "{$ info["name"]} is a company {$ groups[$role]} ";
?>

This prints "Ghost is a company administrator". in the page.

As you can see, I made some new things. I did not use the numeric keys in the $ groups array because PHP solves them by default, and I also used the name of $ role in a sentence. I did this because $ role = 2, from the $ info array and $ groups[2]= the name of the group (Administrator). Remember, although 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 a matrix within the matrix. Our "friends" key in the $ info matrix makes our $ info array not only associative, but also a multidimensional matrix. Also, you may have noticed that the $ info[“friends”] that is your own matrix is ​​a numerical matrix.

If we wanted to meet the first friend of this user, we could do …

Code:

echo $ info["friends"][0];

This will print "Frank" on the page because that is key 0 of the friends array: the first result.

Now let's go through our matrix.
We love the loops because they are perfect for repetitive functions. Instead of executing duplicate code for each element of the array, a loop will search all the different values ​​within the array and do things with it. We will go through our array of friends to do things with each other.

tutorial.php

Code:

"Ghost", "age" => 25, "role" => 2, "friends" => array ("Frank", "James", "Chris")); // associative matrix

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

$ role = $ info["role"];
echo "{$ info["name"]} is a company {$ groups[$role]} 
"; // FOREACH LOOP foreach ($ info["friends"] like $ friend) { echo $ friend "is a friend of {$ info["name"]}
"; } ?>

In this example we see the following printed on the page.:
Ghost is an administrator of the company.
Frank is a friend of Ghost.
James is a friend of Ghost.
Chris is friends with Ghost.

This is because we use a foreach loop to do the same with each matrix value. We are saying "for each name in the array of friends … do something". Also, the syntax is quite simple, since foreach ($ array as $ variable) is easy to remember.

We could also change foreach to show some keys / matrix labels for values ​​like this … This adds an additional piece to our foreach statement by dividing the key 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 repeat everything except a matrix value, but in general, you will use most loops when you want to do the same with each value. In general, it will not pass through several matrix values ​​if all of them require a separate logic depending on the key, but there are times when it may be necessary.

Code:




foreach ($ info as $ key => $ value) {
echo "$ key";
}

This would be printed …
"name age role friends", because those are the key names in our matrix. Then, as we separate the key and the value in separate variables in our foreach, we can access both the name of the key and the value itself.

Consider the following …

Code:

"value1", "key2" => "value2");
foreach ($ arr as $ key => $ value) {
echo "The key $ is $ value 
"; } ?>

This shows:
The key1 is value1
The key2 is value2

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

We need to know the amount of values ​​within the matrix.

tutorial.php

Code:

"Ghost", "age" => 25, "role" => 2, "friends" => array ("Frank", "James", "Chris")); // associative matrix

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

$ role = $ info["role"];
echo "{$ info["name"]} is a company {$ groups[$role]}, and it's {$ info["age"]year old. 
"; $ num = count ($ info["friends"]); // count the number of values ​​in the matrix info => friends for ($ x = 0; $ x <$ num; $ x ++) { echo $ info["friends"][$x] . "is a friend of {$ info["name"]}
"; } ?>

In this example we see the following printed on the page.:
Ghost is an administrator of the company, and he is 25 years old.
Frank is a friend of Ghost.
James is a friend of Ghost.
Chris is friends with Ghost.

We are going to break the for loop.
We begin by obtaining the value of $ num. It's the number of friends, which is 3.
Then we start our for loop with a new variable that we call $ x.
$ x = 0
Then we say $ x <$ num. This means that our for loop will begin with $ x equal to 0, and will be repeated as long as $ x remains less than (<) $ num or in other words, while $ x is less than 3.

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

Therefore, in our for loop, $ x starts at 0. Each time the loop is executed, it increases by 1, and will continue to loop while $ 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 be equal to 3, and the loop stops because our rules they say that the loop should only be executed if $ x is LESS THAN 3, it is not equal to it.

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

So, our 3 loops are accessing the friend's name in this way:
$ info[“friends”][0]
$ info[“friends”][1]
$ info[“friends”][2]

Because 0, 1, 2 are the values ​​of our variable $ x 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, the arrays start at 0 by default for the keys)

You may wonder why we use loops. Well, the loops are perfect for when the amount of information can vary in quantity. If all people have only one age and one name, we do not need to complete the information. However, for things like friends where people can have 0 friends, 3 friends or even hundreds of friends, the loops allow us to execute code for each value in the matrix, regardless of the amount. They can even duplicate each other: a loop inside a loop. This could be taken further to have dozens of nested loops, but there are very few cases where it would be necessary. The loops are good, but they can definitely get out of control.

For large amounts of data, it is important that you do not make your script / page load forever due to a large loop. An example of this would be a forum with 1 million publications in a category. Instead of looping through all 1 million content, we would get the first 25-100 results instead and we would do it. We would pass 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're not running unnecessary loops in Big Data unless you really have to.

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

tutorial.php

Code:

"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 matrix info => friends
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 greater than ours
$ data[] = $ info["friends"][$x]; // add this friend to the data matrix
}

} // end of for loop

print_r ($ data);
?>

In this last example we are really putting everything together.
We start with an empty matrix, $ data.
We also have our $ info matrix that stores our name, age and our friends. The friends array contains several arrangements, which have information about the friend. When we go through the friends matrix, we can access the information of each friend using the appropriate matrix key (name or age). In this example, we are trying to find all the friends who are older than us. We discovered correctly that Chris and James are older than us, so they are added to the $ data matrix.

The result would be the same as creating the $ data array in this way:

Code:

"Chris", "age" => 26), array ("name" => "James", "age" => 27));
?>

So, as you can see, you can access the data in the matrix with the loop, analyze them and then do things with that information, like building the $ data matrix separately so that only our older friends have it. Obviously, this is a very specific example, but you can do much more, including echo values ​​on the page, trigger another script to execute, or really anything you can imagine.