Associative Arrays In PHP
PHP associative arrays, refers to a collection of elements that are stored as a pair of key-value pairs in a single variable.
We will explore how PHP associative arrays works, how to create them, and how to manipulate them in this article.
In associative arrays, the index can be a string, a number, or even another variable, unlike indexed arrays, where the index is an integer. It’s easy to retrieve and manipulate data based on a key.
PHP Associative Arrays
With PHP Arrays Associative, you can use named keys to assign keys to arrays.
PHP associative arrays can be created in two ways:
$marks = array( "Science"=>90, "Mathematic"=>80, "English"=>86, "Computer Studies"=>84, "Geography"=>96);
Or second method to create an associative array is:
$john_marks["Science"] = 90; $john_marks["Mathematic"] = 80; $john_marks["English"] = 86; $john_marks["Computer Studies"] = 84; $john_marks["Geography"] = 96;
Scripts can then be written by using the named keys as follows:
PHP Associative Array Loop
In order to loop through an associative array, there are a variety of techniques that can be used.
As an example of how to loop through an associative array in PHP, here is the most common way that you may find useful.
Foreach loops are commonly used in PHP to loop associative arrays.
For each iteration, a block of code will be executed over each pair of keys-values in the array.
Following is an example of looping through each element of an associative array:
Here is another example for clear understanding of looping through elements of an associative array:
First we have created an associative array called $user_info. It uses a foreach loop to iterate over its elements and print the keys and values to the screen.
The $user_info array contains four elements, each with a string key and a corresponding value.
The keys are “FirstName”, “LastName”, “Age”, and “Gender”, and their respective values are “Mark”, “Zuckerberg”, 38, and “M”.
The foreach loop uses two variables, $field and $value, to represent the key and value of each element in the array.
The $field variable represents the key or field name, while the $value variable represents the corresponding value.
The echo statement inside the loop is used to print the key and value of each element of the array to the screen. This is separated by an equal sign and a space. The line break <br> is used to move to a new line after each key-value pair.
So, when the loop is executed, the output will be:
This is because the loop iterates over each element of the $user_info array and prints its key and value to the screen.