Learning arrays in PHP. PHP Arrays: Multidimensional, Associative and Numeric Arrays What is stored in PHP associative arrays

Array is a data structure that stores one or more identical values in one meaning. For example, if you want to store 100 numbers, then instead of defining 100 variables, it is easy to define an array of length 100.

There are three different types arrays, and each array value is accessed by an identifier c called array index.

  • Numeric array- an array with a numeric index. Values ​​are stored and accessed in a linear manner.
  • Associative Array- an array with strings as an index. This stores element values ​​in combination with key values ​​rather than a strict linear index order.
  • Multidimensional array. An array containing one or more arrays and values ​​is accessed using multiple indexes

Numeric array

These arrays can store numbers, strings and any object, but their index will be represented by numbers. By default, the array index starts at zero.

Example

Below is an example of creating and accessing numeric arrays.

Here we have used the array() function to create an array. This feature is explained in the feature description.

Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays

Associative arrays are very similar to numeric arrays in terms of functionality, but they differ in the index. An associative array will have its index as a string so that you can establish a strong relationship between the key and the values.

To store employee salaries in an array, a numeric index array would not be best choice. Instead, we could use the employee names as keys in our associative array, and the value would be their corresponding salary.

NOTE. Don't store the associative array inside a double quote while printing, otherwise it won't return any value.

Example

2000, "qadir" => 1000, "zara" => 500); echo "Salary of mohammad is ". $salaries["mohammad"] . " "; echo "Salary of qadir is ". $salaries["qadir"]. " "; echo "Salary of zara is ". $salaries["zara"]. " "; /* Second method to create array. */ $salaries["mohammad"] = "high"; $salaries["qadir"] = "medium"; $salaries["zara"] = "low"; echo "Salary of mohammad is ". $salaries["mohammad"] . " "; echo "Salary of qadir is ". $salaries["qadir"]. " "; echo "Salary of zara is ". $salaries["zara"]. " "; ?>

This will produce the following output -

Salary of Mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional arrays

Multidimensional Array Each element in the main array can also be an array. And each element in the sub-array can be an array and so on. Values ​​in a multidimensional array are accessed using multiple indexes.

Example

In this example, we create a two-dimensional array to store the marks of three students in three subjects. This example is an associative array, you can create a numeric array in the same way.

array ("physics" => 35, "maths" => 30, "chemistry" => 39), "qadir" => array ("physics" => 30, "maths" => 32, "chemistry" => 29), "zara" => array ("physics" => 31, "maths" => 22, "chemistry" => 39)); /* Accessing multi-dimensional array values ​​*/ echo "Marks for mohammad in physics: " ; echo $marks["mohammad"]["physics"] . " "; echo "Marks for qadir in maths: "; echo $marks["qadir"]["maths"] . " "; echo "Marks for zara in chemistry: " ; echo $marks["zara"]["chemistry"] . " "; ?>

This will produce the following output -

In this article, we continue to learn the basics of PHP and get introduced to arrays. Separately, using examples, we will look at creating a regular array, then we will smoothly move on to associative and multidimensional arrays. The material presented will be enough to firmly grasp the next part of PHP basics, namely PHP arrays.

PHP Arrays – What are PHP arrays and how are they created. Simple (index) arrays

Arrays in PHP play a very important role and are widely used when building websites. An array is a so-called variable (), which can contain several values ​​available at certain indexes. To access array information, simply specify the array name and the index of the data cell. For clarity, I will give an example of the structure of a simple index array and a variable.

As you can see from the image, the difference between an array and a variable is not very big. A variable can only take one value, but an array can have several values ​​at once. Moreover, in order to extract information from an array, it is enough to simply indicate the name of the array and the index for which the information is available. For a more complete understanding, let's look at an example and create an array, then extract information from it and display it on the screen.

/*Creating an array*/ $name = "A"; $name = "B"; $name = "C"; $name = "D"; $name = "E"; /*Output the value of the array cell with index 2 to the screen*/ echo $name;

In the above example, we can see that we first create the first element of the array with index "0" and assign the value "A" to it. Then we create the remaining 4 elements of the array in the same way. After this, using echo operator we display the third element of the array to the screen. As you have already noticed, in order to display an array element on the screen, you need to specify the name of the array and the index of the cell with the data.

In addition to the above method, an array in PHP can be created in another way. Its essence is to use keyword array. For clarity, let's look at the same example of creating an array, but in a different way.

$name = array (0 => "A", 1 => "B", 2 => "C", 3 => "D", 4 => "E");

This method is also very simple. To create an array, we create a $name variable, then put an assignment sign “=” and indicate that it is an array. After that, we create cells and fill them with data. This is done by specifying an index and assigning a value to it using the “=” and “>” signs. That is, “0 => “A”” means that we assign the value “A” to the cell with index “0”. It’s a little awkward to explain this topic in text, but I think you understand what I’m talking about.

I would also like to immediately note that if the index of the first element in the array being created is zero, then the indices do not need to be entered. In this case, PHP will add indexes automatically starting from zero. All this will look like this.

First option for creating arrays in PHP

$name = "A"; $name = "B"; $name = "C"; $name = "D"; $name = "E";

Second option for creating arrays in PHP

$name = array("A", "B", "C", "D", "E");

PHP Associative Arrays

Associative arrays are another type of PHP array. The difference between associative arrays and simple arrays is the indexes. If in simple arrays these were numeric indices, then in associative arrays these indices are text. This makes associative arrays more organized and meaningful. Due to this, they are more widely used than simple index ones.

Associative arrays are created in a similar way. Let's consider 2 main methods.

The first way to create an associative array.

$color["white"] = "white"; $color["black"] = "black"; $color["red"] = "red"; $color["green"] = "green"; $color["blue"] = "blue";

The second way to create an associative array.

$color = array("white" => "white", "black" => "black", "red" => "red", "green" => "green", "blue" => "blue") ;

As you can see, the procedure for creating an associative array is identical to the procedure for creating an index one. In order to display an array element on the screen, we can use the . Let's consider two methods - the usual one and using variable docking.

Echo "Selected color - $color"; echo "The color selected is ".$color["red"].";

As you already noticed, in the first case the cell index is not enclosed in double quotes. This rule should be remembered immediately in order to avoid mistakes in the future. If you use the first method and want to display an array element without joining variables, then the index is not quoted. In the second example, as you can see, everything is written as usual and the quotes are not removed.

Personally, I like the first method better, since, in my opinion, it is much more easier than the second and requires less movement to implement. However, it is up to you to choose which method you will use.

Now let's move on to the final part of the article and look at PHP multidimensional arrays.

PHP Multidimensional Arrays

A multidimensional array is an array that contains another array. For clarity, let's implement a multidimensional array using three types of computers as an example. In our case, this is a desktop computer, laptop and netbook. The characteristics will be volume random access memory, volume hard drive and processor frequency. Schematically, a multidimensional PHP array for solving this problem may look like this.

You can create a multidimensional array, like all others, in several ways. In order to save time, we will consider only the second method. I think you've already memorized how arrays are created in PHP and you shouldn't have any problems with it.

$massiv["Desktop PC"] = array ("RAM" => "4096", "HDD" => "500", "GC" => "3"); $massiv["Laptop"] = array ("RAM" => "3072", "HDD" => "320", "GC" => "2"); $massiv["Netbook"] = array ("RAM" => "2048", "HDD" => "250", "GC" => "1.6");

In order to display an element of a multidimensional array on the screen in PHP, it is enough to use the echo output operator and the variable docking method, since otherwise (without variable docking) the element of the multidimensional array will not be displayed on the screen. This is another difference when working with PHP multidimensional arrays.

Echo "A desktop PC with RAM capacity ".$massiv["Desktop PC"]["RAM"]." and hard drive capacity ".$massiv["Desktop PC"]["HDD"]." has a processor frequency of " . $massiv["Desktop PC"]["GC"]. "GC.";

Now let's summarize all of the above.

In this article, we looked at three types of arrays - index, associative and multidimensional. We learned how to create arrays in PHP, as well as how to pull out an array element and display it on the screen. The basics of working with arrays were covered, as well as some rules for displaying elements on the screen.

This concludes this article. If you don't want to miss latest updates blog, you can subscribe to the newsletter in any way convenient for you in the “” section or use the form below.

That's all. Good luck to you and see you soon on the blog pages

Last update: 11/1/2015

Arrays are designed to store sets of data or elements. Each element in the array has its own unique key and value. So, let’s save the list of phone models into an array:

Samsung Galaxy ACE II"; $phones = " Sony Xperia Z3"; $phones = "Samsung Galaxy III"; for($i=0;$i "; ?>

Here an array $phones is created with four elements. Each element in the array represents a key-value pair. So, the first element $phones = "Nokia N9" has a key - the number 0, and a value - the string "Nokia N9". In such arrays, the numeric keys are also called indexes.

You can use the count() function to find out the number of elements in an array. And due to the fact that the keys are in order from 0 to 3, and knowing the size of the array, you can display the array elements in a for loop.

To make the relationship between the keys and values ​​of the elements more clear, let’s print the array using the print_r function:

Print_r($phones);

We will get the following output:

Array ( => Nokia N9 => Samsung Galaxy ACE II => Sony Xperia Z3 => Samsung Galaxy III)

This array creation would also be equivalent to the following:

"; ?>

If an element key is not specified, PHP uses numbers as keys. In this case, the numbering of keys starts from zero, and each new key increases by one.

Knowing the key of an element in an array, we can access this element, get or change its value:

// get the element by key 1 $myPhone = $phones; echo "$myPhone
"; // assigning a new value $phones = "Samsung X650"; echo "$phones
";

But not only integers, but also strings can be used as keys:

Such arrays are also called associative.

array operator

One way to create an array was discussed above. But there is another one, which involves the use of the array() operator.

The array() operator takes a set of elements. The keys are also not explicitly specified here. Therefore, PHP automatically numbers elements from zero. But we can also specify a key for each element:

"iPhone5", "samsumg"=>"Samsung Galaxy III", "nokia" => "Nokia N9", "sony" => "Sony XPeria Z3"); echo $phones["samsumg"]; ?>

The => operation allows you to map a key to a specific value.

Iterating over associative arrays

Above we looked at how to use for loop print all the elements of an array where the keys are given sequentially by numbers from 0 to 3. However, this does not work with associative arrays. And for them, PHP has a special type of loop - foreach...as :

"iPhone5", "samsumg"=>"Samsung Galaxy III", "nokia" => "Nokia N9", "sony" => "Sony XPeria Z3"); foreach($phones as $item) echo "$item
"; ?>

In a foreach loop, all elements are sequentially removed from the array and their value is placed in the variable specified after the as keyword. In this case, all four values ​​from the $phones array are placed in the $item variable in turn. When the last element from the array is retrieved, the loop ends.

The foreach loop allows you to retrieve not only values, but also element keys:

"iPhone5", "samsumg"=>"Samsung Galaxy III", "nokia" => "Nokia N9", "sony" => "Sony XPeria Z3"); foreach($phones as $key=>$value) echo "$key => $value
"; ?>

Here, when iterating through the elements of the loop, the key of the element will be transferred to the $key variable, and its value will be transferred to the $value variable.

Alternative foreach loop represents the use of the list and each functions:

"iPhone5", "samsumg"=>"Samsung Galaxy III", "nokia" => "Nokia N9", "sony" => "Sony XPeria Z3"); while (list($key, $value) = each($phones)) echo "$key => $value
"; ?>

The while loop will run until the each function returns false . The each function iterates through all the elements of the $phones array and returns it as an array that includes the element's key and value. This array is then passed to the list function and the array values ​​are assigned to the variables inside the parentheses. When the each function has finished iterating through the $phones array, it will return false and the while loop will end.

Multidimensional arrays

In the previous examples, only one-dimensional arrays were considered, where the element values ​​represented numbers or strings. But in PHP, arrays can also be multidimensional, that is, ones where an element of the array is itself an array. For example, let's create a multidimensional array:

array("iPhone5", "iPhone5s", "iPhone6") , "samsumg"=>array("Samsung Galaxy III", "Samsung Galaxy ACE II"), "nokia" => array("Nokia N9", " Nokia Lumia 930")), "sony" => array("Sony XPeria Z3", "Xperia Z3 Dual", "Xperia T2 Ultra")); foreach ($phones as $brand => $items) ( echo "

$brand

"; echo "
    "; foreach ($items as $key => $value) ( ​​echo "
  • $value
  • "; ) echo "
"; } ?>

And when outputting, we will get 4 lists:

To access a given element, you must also specify the keys in square brackets. For example, let's look at the first element in the first array. Since the key of the first array is "apple" and the key of the first element in the first array is the number 0 (since we didn't explicitly specify the keys):

Echo $phones["apple"];

You can get the second element of the third array in a similar way:

Echo $phones["nokia"];

Let's say nested arrays also represent associative arrays:

array("apple" => "iPhone5", "samsumg" => "Samsung Galaxy III", "nokia" => "Nokia N9"), "tablets" => array("lenovo" => "Lenovo IdeaTab A3500" , "samsung" => "Samsung Galaxy Tab 4", "apple" => "Apple iPad Air")); foreach ($technics as $tovar => $items) ( echo "

$product

"; echo "
    "; foreach ($items as $key => $value) ( ​​echo "
  • $key: $value
  • "; ) echo "
"; ) // assign a different value to one of the elements $technics["phones"]["nokia"] = "Nokia Lumnia 930"; // display this value echo $technics["phones"]["nokia"]; ? >

Associative Array– an irreplaceable data type used to describe a collection of unique keys and associated values ​​– is a basic element of all programming languages, including PHP. In fact, associative arrays play such an important role in web programming that PHP includes support for a variety of functions and properties that can manipulate arrays of data in every imaginable way. This extensive support can be overwhelming for developers looking for the most effective ways managing arrays in your applications. In this article, I'll share 10 tips that will help you slice, dice, and shred your data in an endless number of ways.

1. Adding array elements.

PHP - weak typed language, i.e. it does not need to describe in detail either the array or its size. Instead, the array can be declared and populated at the same time:

$capitals = array("Alabama" => "Montgomery", "Alaska" => "Juneau", "Arizona" => "Phoenix");

Additional array elements can be appended in the following way:

$capitals["Arkansas"] = "Little Rock";

If you work with numbered arrays and would prefer to append elements (to the beginning of the array) and append elements using a verbose-named function, consider the array_push() and array_unshift() functions (these functions do not work with associative arrays).

2. Removing array elements

To remove an element from an array, use the unset() function:

Unset($capitals["California"]);

By working with numbered arrays, you have more freedom when it comes to deleting array elements. That is, you can use the array_shitt() and array_pop() functions to remove an element from the beginning and end of the array, respectively.

3. Swap keys and values

Let's say you wanted to create a new array called $states with the state capitals as indexes and the states themselves as associative values. This task (switching keys and values) is easily solved using the array_flip() function:

$capitals = array("Alabama" => "Montgomery", "Alaska" => "Juneau", "Arizona" => "Phoenix"); $states = array_flip($capitals); // $states = array(// "Montgomery" => string "Alabama", // "Juneau" => string "Alaska", // "Phoenix" => string "Arizona" //);

4. Merging arrays

Let's assume that the previous array was used in combination with a web-based "flash card" (flashcard - a card with text and a picture (used in training) foreign language)) service and you wanted to give students the opportunity to test their knowledge not only about world capitals, but also the capitals of the United States. You can merge an array (with state capitals) with an array (with world capitals) using the array_merge() function:

$stateCapitals = array("Alabama" => "Montgomery", "Alaska" => "Juneau", "Arizona" => "Phoenix"); $countryCapitals = array ("Australia" => "Canberra", "Austria" => "Vienna", "Algeria" => "Algiers"); $capitals = array_merge($stateCapitals, $countryCapitals);

5. Editing array values

Let's assume that the data found in the array may contain errors related to the use of capital letters, and you want to correct these errors before entering the data into the database. In this case, you can use the array_map() function to apply a callback function to each element of the array:

Function capitalize($element) ( $element = strtolower($element); // Convert all letters to lowercase return ucwords($element); // Convert the first character of each word in the line to uppercase ) $capitals = array(" Alabama" => "montGoMEry", "Alaska" => "Juneau", "Arizona" => "phoeniX"); $capitals = array_map("capitalize", $capitals);

6. Sort arrays by keys

Flashcard applications (flashcard - a card with text and a picture (used when teaching a foreign language)) resort to various teaching techniques, including sorting cards in certain ways, for example, alphabetically. You can sort associative arrays by keys using the ksort() function:

$capitals = array("Arizona" => "Phoenix", "Alaska" => "Juneau", "Alabama" => "Montgomery"); ksort($capitals);

7. Array order randomization

You can shuffle elements in random order using the shuffle() function:

$capitals = array("Arizona" => "Phoenix", "Alaska" => "Juneau", "Alabama" => "Montgomery"); shuffle($capitals); foreach ($capitals as $k=>$v) echo "$k: $v
";

Result:

Please note at the exit we get not an associative array, but a numeric array.

If, instead of randomizing the array, you want to select a value at random, use the array_rand() function.

8. Determine whether keys and values ​​exist

You can use the in_array() function to determine whether array elements exist:

$capitals = array("Arizona" => "Phoenix", "Alaska" => "Juneau", "Alabama" => "Montgomery"); if (in_array("Juneau", $capitals)) ( echo "Exists!"; ) else ( echo "Does not exist!"; )

The ability to determine whether array keys exist is less known. It is implemented using the array_key_exists() function:

$capitals = array("Arizona" => "Phoenix", "Alaska" => "Juneau", "Alabama" => "Montgomery"); if (array_key_exists("Alaska", $capitals)) ( echo "Key exists!"; ) else ( echo "Key does not exist!"; )

9. Looking for an array

You might want to provide a searchable flashcard resource so that users can easily find the state associated with a specific capital city. This can be done using the array_search() function (this function searches an array for a given value and returns the corresponding key):

$capitals = array("Arizona" => "Phoenix", "Alaska" => "Juneau", "Alabama" => "Montgomery"); $state = array_search("Juneau", $capitals); // $state = "Alaska"

10. Standard PHP library

Standard PHP library(SPL) provides developers with a fair number of data structures, interfaces, exceptions, and other properties that were previously PHP language I couldn't brag. Among these properties is the ability to iterate (repeate) an array using object-oriented syntax.

$capitals = array("Arizona" => "Phoenix", "Alaska" => "Juneau", "Alabama" => "Montgomery"); $arrayObject = new ArrayObject($capitals); foreach ($arrayObject as $state => $capital) ( printf("The capital of %s is %s
", $state, $capital); ) // The capital of Arizona is Phoenix // The capital of Alaska is Juneau // The capital of Alabama is Montgomery

This is just one of the cool features included in SPL. For more information, check out the PHP documentation.

Associative Arrays

Simple arrays use keys only to separate elements and have no practical value:

In associative arrays, the keys describe what kind of value they contain - age, name, etc.:

"Vladimir", "age" => 20]; ?>

Two-dimensional and multidimensional arrays

So far we've only dealt with one-dimensional arrays, but we can also create a two-dimensional or any multi-dimensional array:

"Vasya"]; $human["hands"] = ["left", "right"]; print_r($human); ?>

As you can see, we created an array $human and then inside it we created another array $human["hands"] . Result in browser:

Array ( => Vasya => Array ( => left => right))

We can create multidimensional arrays of any nesting. The output of such an array looks like this:

Practical application of multidimensional arrays

Remember in the previous lesson we wanted to group products and their characteristics? Let me remind you of the code we got:

Now we can put all this information into one variable. In this case, each product will be an associative array, and all products will be located inside a simple array:

"iPhone", "price" => 5000, "quantity" => true ], [ "name" => "Samsung Galaxy", "price" => 5000, "quantity" => true ], [ "name" = > "Nokia Lumia", "price" => 4000, "quantity" => true ] ]; ?>

Or alternatively:

"iPhone", "price" => 5000, "quantity" => true ]; $products = [ "name" => "Samsung Galaxy", "price" => 5000, "quantity" => true ]; $products = [ "name" => "Nokia Lumia", "price" => 4000, "quantity" => true ]; ?>

The result of both options will be:

Array ( => Array ( => iPhone => 5000 => 1) => Array ( => Samsung Galaxy => 5000 => 1) => Array ( => Nokia Lumia => 4000 => 1))

1. Create an array $city , add the name key with any value to it. 2. Create a streets subarray with any random streets. Each street must have a name (name) and a number of houses (buildings_count), as well as a subarray of house numbers (old_buildings) to be demolished.