Menu
Is free
registration
home  /  Problems/ Types of arrays in PHP. Declaring an array in php, types of arrays and working with php elements go deep into an associative array

Array types in PHP. Declaring an array in php, types of arrays and working with php elements go deep into an associative array

Associative arrays

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

In associative arrays, 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 multidimensional 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 the browser:

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

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

Practical Applications of Multidimensional Arrays

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

Samsung Galaxy"; $ product2_price = 5000; $ product2_quantity = true; $ product3_name =" Nokia Lumia"; $ product3_price = 4000; $ product3_quantity = true;?>

Now we can put all this information into one variable. Moreover, each product will be an associative array, and all products will be 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]; ?>

Both options will result in:

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 subarray of streets 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.

Associative array- an indispensable data type used to describe a collection of unique keys and associative values ​​- is the basic element of all programming languages, including PHP. As such, associative arrays play such an important role in web programming that PHP includes support for many functions and properties that can manipulate arrays of data in every conceivable way. This extensive support can be cumbersome for developers looking for the most effective ways manage arrays in their applications. In this article, I'll provide 10 tips to help you slice, shred, and shred your data in an infinite number of ways.

1. Adding array elements.

PHP is a weakly typed language, that is, it does not need to describe in detail either the array or its size. Instead, an array can be declared and populated at the same time:

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

Additional array elements can be attached in the following way:

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

If you are working with numbered arrays and would prefer to append elements (to the beginning of the array) and attach elements using the well-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"]);

Working with arrays numbered with numbers gives you 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

Suppose you wanted to create a new array called $ states, with state capitals as indices and states as associative values. This task (swapping the keys and values) can be 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

Suppose the previous array was used in combination with a web-based "flash card" foreign language)) service and you wanted to give students the opportunity to test their knowledge not only of the world capitals, but also of the capitals of the United States. You can combine 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

Suppose 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 to uppercase the first character of each word in the string) $ capitals = array (" Alabama "=>" montGoMEry "," Alaska "=>" Juneau "," Arizona "=>" phoeniX "); $ capitals = array_map ("capitalize", $ capitals);

6. Sort arrays by keys

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

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

7. Randomizing the order of the array

You can shuffle the items 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:

Pay attention to the output we get not an associative array, but a numeric array.

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

8. Determine if keys and values ​​exist

You can use the in_array () function to determine if 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 if array keys exist is less well 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 search engine to your flashcard so that users can easily find the state associated with a particular capital city. This can be done using the array_search () function (this function searches the array set value and returns the corresponding key):

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

10. PHP standard library

The PHP Standard Library (SPL) provides developers with a decent number of data structures, interfaces, exceptions, and other properties that used to be PHP language could not boast. Among these properties is the ability to iterate (repeat) 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 the SPL. Check out the PHP documentation for more information.

Array elements in PHP can contain values ​​of any type, such as numbers, strings, objects. They can also contain other arrays, which actually means creating multidimensional or nested array.

V this lesson multidimensional (nested) PHP arrays are considered. Explains how to create them, how to manipulate them, how to loop through an entire multidimensional array in PHP.

How to create a multidimensional array

You can create a multidimensional array using the array () construct, which is very similar to creating a regular array. The difference is that in a multidimensional array, each element is also an array.

For example:

$ myArray = array (array (value1, value2, value3), array (value4, value5, value6), array (value7, value8, value9));

The above example creates a two-dimensional array. Array top level contains 3 elements. Each element is also an array containing 3 values.

You can also use an associative array as a multidimensional array. The following example demonstrates creating an indexed array that contains 3 associative arrays:

$ movies = array (array ("title" => "Rear Window", "director" => "Alfred Hitchcock", "year" => 1954), array ("title" => "Full Metal Jacket", "director "=>" Stanley Kubrick "," year "=> 1987), array (" title "=>" Mean Streets "," director "=>" Martin Scorsese "," year "=> 1973));

You can nest arrays as deeply within one another as needed (although in practice the nesting depth is rarely more than 3 levels). The example below demonstrates a 3-dimensional array:

$ myArray = array (array (array (value1, value2), array (value3, value4)), array (array (value5, value6), array (value7, value8)));

Accessing elements in a multidimensional array

To access the elements of a multidimensional array, you can use the "square brackets" syntax, which is used to work with a regular array. If you need to access second-level elements in a two-dimensional array, you just need to use the second set of square brackets, for example:

$ myArray = array (array ("one", "two", "three"), array ("four", "five", "six")); // Print "six" echo $ myArray; ?>

And here's an example that demonstrates how to access various elements of the multidimensional $ movies array we created earlier:

Echo "Title of the first film:
"; echo $ movies [" title "]."

"; echo" Third film director:
"; echo $ movies [" director "]."

"; echo" The nested array that is contained in the first element:
"; print_r ($ movies); echo"

";

Executing the code will produce the following output:

First movie title: Rear Window Third movie director: Martin Scorsese The nested array contained in the first element: Array (=> Rear Window => Alfred Hitchcock => 1954)

The last example uses $ movies to access the entire nested array in the first element of the top-level array, and then uses the print_r () function to display the contents of the array.

Organization of iteration over all elements of a multidimensional array in a loop

Just like for a regular one-dimensional array, you can use foreach to iterate over all the elements of a multidimensional array. We need to create a nested foreach loop, that is, one loop inside another:

  1. The outer loop takes each element of the top-level array.
  2. For each top-level element, the inner loop iterates over the nested array, and so on.

The example creates a 2-dimensional array with information on films, and then organizes a loop over the array elements to display the information on the page:

$ movies = array (array ("title" => "Rear Window", "director" => "Alfred Hitchcock", "year" => 1954), array ("title" => "Full Metal Jacket", "director "=>" Stanley Kubrick "," year "=> 1987), array (" title "=>" Mean Streets "," director "=>" Martin Scorsese "," year "=> 1973)); foreach ($ movies as $ movie) (echo "

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

Executing this code will produce the following output:

Title Rear Window director Alfred Hitchcock year 1954 title Full Metal Jacket director Stanley Kubrick year 1987 title Mean Streets director Martin Scorsese year 1973

Summary

Multidimensional arrays are suitable for storing any kind of data, for example, for storing multiple database records or values ​​for display in tables. Using multidimensional arrays can increase the level of functionality of PHP scripts.

The lesson will consider the possibilities for working with arrays in php, declaring an array, types of arrays: multidimensional and associative arrays

  1. Arrays with numeric indices
  2. $ fruits = "apple"; $ fruits = "pear"; $ fruits = "orange"; $ fruits = "apricot";

    This variant of array initialization is practically not used today. The following way of working with arrays is used:

  3. Associative array
  4. This variant of creating an array uses the array object:

    $ fruits = array (1 => "apple", 2 => "pear", 3 => "orange", 4 => "apricot"); // Beginning with PHP versions 5.4 $ fruits = array [1 => "apple", 2 => "pear", 3 => "orange", 4 => "apricot"];

    Accessing array elements

    1 2 3 4 5 6 7 8 $ fruits [0] = "apple"; $ fruits [1] = "pear"; $ fruits [2] = "orange"; $ fruits [3] = "apricot"; echo "The first element of the array is"... $ fruits [0]. "
    "; echo "The second element of the array is"... $ fruits [1]. "
    "; echo "The third element of the array is"... $ fruits [2]. "
    " ;

    $ fruits = "apple"; $ fruits = "pear"; $ fruits = "orange"; $ fruits = "apricot"; echo "The first element of the array is". $ fruits. "
    "; echo" The second element of the array is ". $ fruits."
    "; echo" The third element of the array is ". $ fruits."
    ";

    The result of executing the program will be:

    Important: The index of an element in an associative array can be not a number, but a word (type string)

    Let's consider an example:

    Example: Create an array student with the values ​​of names, surnames and ages of students. Display the values ​​of array elements

    $ student = array ("Name" => John, "Surname" => Smith, "Age" => 20); echo "username". $ student ["Name"]. "


    ";

    $ student ["Name"] = "John"; $ student ["Surname"] = "Smith"; $ student ["Age"] = 20; echo "username". $ student ["Name"]. "
    "; echo" user's last name ". $ student [" Surname "]."
    "; echo" user age ". $ student [" Age "]."
    ";

    Result:

    Important: String keys (indexes) must always be quoted

    Keyless indexed arrays:

    It should also be noted that the indices in the array do not need to be written at all when the array is initialized with values. Then we create the so-called array-collection(collection object):

    $ student = array ("John", "Smith", 20);

    $ student = array ("John", "Smith", 20);

    In this case, the interpreter itself will assign them numerical indices, starting from 0

    Example type conversions and element rewriting.
    Note the use of the var_dump () routine

    1 2 3 4 5 6 7 8 9 "a", "1" => "b", 2 => "c", 2 => "d",); var_dump ($ my_array); ?>

    "a", "1" => "b", 2 => "c", 2 => "d",); var_dump ($ my_array); ?>

    Result:

    Array (3) (=> string (1) "a" => string (1) "b" => string (1) "d")

    Example use of multidimensional array and organizing access to its elements

    1 2 3 4 5 6 7 8 9 10 11 12 "1", 2 => 2, "multi" => array ("1_1" => "1_1")); var_dump ($ array_odnom ["first"]); var_dump ($ array_odnom [2]); var_dump ($ array_odnom ["multi"] ["1_1"]); ?>

    "1", 2 => 2, "multi" => array ("1_1" => "1_1")); var_dump ($ array_odnom ["first"]); var_dump ($ array_odnom); var_dump ($ array_odnom ["multi"] ["1_1"]); ?>

    Result:

    String (1) "1" int (2) string (3) "1_1"

    Example: create a two-dimensional array with dimensions 3 x 2. Fill it with the values ​​for the first line: "1_1", "1_2", "1_3"; for the second line: "2_1", "2_2", "2_3". Display the first element of an array


    Performance:
    1 2 3 4 5 6 7 8 9 10 11 12 $ array_odnom = array (1 => array (1 => "1_1", 2 => "1_2", 3 => "1_3"), 2 => array (1 => "2_1", 2 => "2_2" , 3 => "2_3"),); echo $ array_odnom [1] [1];

    $ array_odnom = array (1 => array (1 => "1_1", 2 => "1_2", 3 => "1_3"), 2 => array (1 => "2_1", 2 => "2_2" , 3 => "2_3"),); echo $ array_odnom;

    Php2_1 job: create a 2-dimensional array 3 x 3 - upper left corner of the Pythagorean multiplication table (1, 2, 3; 4, 6, 8 ...)



    Laboratory work:
    Let's say you have some kind of ad and several different people who need to send this ad. To do this, you make a template with the content of the ad, inside which there are a number of changing parameters: an array of people 's names and an array of events. Display one variant of the final ad on the screen. To specify arrays, use an associative array as well.

    Use an ad template and be guided by the colors:

    Red - arrays.
    Brown is a numeric variable.
    Blue is a constant.

    Dear Ivan Ivanovich!
    We invite you to Open Day.
    Event date: 12 May.
    Best regards, Vasily.


    Complete the code:
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 // constant declaration define ("SIGN", "Best regards, Vasya") ; // array for recipient names$ names = array (...); // array for events$ events = array ("op_doors" => "Open Day", "vistavka" => "exhibition", ...); $ str = "Dear, $ names!
    "
    ; $ str. = ...; $ str. = ...; echo ...;

    // constant declaration define ("SIGN", "Sincerely, Vasya"); // array for recipient names $ names = array (...); // array for events $ events = array ("op_doors" => "open day", "vistavka" => "exhibition", ...); $ str = "Dear, $ names!
    "; $ str. = ...; $ str. = ...; echo ...;

Last update: 1.11.2015

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

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

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

Using the count () function, you can 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 elements of the arrays in the for loop.

To make it clearer the relationship between the keys and values ​​of the elements, we display the array using the print_r function:

Print_r ($ phones);

We get the following output:

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

This array creation will also be equivalent to the following:

"; ?>

If no item key is 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 the array, we can refer to this element, get or change its value:

// get the item 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 that involves the use of the array () operator.

The array () operator takes a set of elements. Keys are not explicitly specified here either. Therefore PHP will automatically number the elements from scratch. 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 match a key to a specific value.

Iterating over associative arrays

Above, we saw how using for loop print all elements of an array, where keys are specified sequentially as numbers from 0 to 3. However, this does not work with associative arrays. And for them in PHP there is 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 the foreach loop, all the elements are sequentially retrieved 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 has been retrieved from the array, the loop ends.

The foreach loop allows you to retrieve not only the values, but also the keys of the elements:

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

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

An alternative foreach loop introduces 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 loops through all the elements of the $ phones array and gets it as an array containing the element's key and value. Then this array is passed to the list function and occurs assigning the values ​​of the array 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 values ​​of the elements represented numbers, strings. But in PHP, arrays can also be multidimensional, that is, where the array element 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 refer to a given item, you also need to 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 number 0 (since we did not explicitly specify the keys):

Echo $ phones ["apple"];

Similarly, you can get the second element of the third array:

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 "

$ tovar

"; 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 "];? >