PHP Array


PHP Array

Array is another data type like number or string. The main difference between an array and other data types is its ability to store more than one value in a variable. In the previous examples, a variable name was always associated with only one value:

  • $name = "PHPclassroom"
  • $age = 42

And if we want to know not only the gender, name and age of the user, but also, say, favorite TV shows? It is very difficult to name one favorite series, but remembering a few is much easier. Saving several values ​​to an array variable looks like this:$fav_shows = ["game of thrones", "american horror story", "walking dead"]

In this example, we have stored $fav_showsthree values in a variable at once. But preserving this data is only half the battle. How to work with them later? The way you are already familiar with displaying a variable on the screen will not work with arrays:

Now we can define an array:
An array is a collection of many elements of the "key: value" type.

Arrays allow you to overwrite existing values ​​and add new ones. You can add a new value to the array as follows: The $fav_shows[] = "the big bang theory"
new element will automatically receive an index equal to the maximum index of the existing ones + 1. The "Big Bang Theory" will be saved in the array under index 3.

If we no longer like one of the series, because the new season turned out to be very bad or a new favorite has appeared, the values ​​in the array can be replaced. To cross out the old value and replace it with a new one, you need to assign a new value to any of the existing indices in the array:$fav_shows[4] = "fargo"

To completely remove (without replacing it with another) a value by its index, there is a function unset:unset($fav_shows[4])

Associative arrays

In the previous section, we got acquainted with the so-called simple arrays. But in PHP there is also a slightly more complex type of arrays - associative. Associative arrays differ from simple ones in that they have keys instead of indices. And if the index is always an integer, ordinal, then the key can be any arbitrary string. That's what it's for. We already know a lot about our user: his name, age, favorite color and TV series. There is only one inconvenience: all this data is now in different variables. It would be convenient to store all this data in one place, and this is where associative arrays come in handy.

Writing all information about a user using an associative array:

Show all information about a user from a variable $user:
print("Hello: " . $user['name'] . " My age: " . $user['age'] . "
List of shows: "  . $user['fav_shows'][0] . ", " . $user['fav_shows'][1] . ", " . $user['fav_shows'][2]);