A Holistic Look at Associative Arrays in PHP

An array refers to a data structure storing one or more related types of values in a single value. For instance, if you are looking to store 100 numbers, instead of specifying 100 variables, you can simply define an array of length 100.N

There are three types of arrays, and you can assess each array value through an ID c, also known as the array index.

  • Numeric Array - It refers to an array with a numeric index. Values are stored and accessed in a linear fashion
  • Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values.
  • Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.

Overview

Associative arrays in PHP store key value pairs. For instance, If you need to store marks earned by a student in different subjects in an array, a numerically indexed array may not be the right choice. A better and more effective option would be to use the names of the subjects as the keys in your associative list, with their respective marks as the value.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

In terms of features, associative arrays are very similar to numeric arrays, but they vary in terms of the index. The index of an associative array is a string that allows you to create a strong link between key and value.

A numerically indexed array is not the best option for storing employee salaries in an array. Instead, you can use the employees' names as keys in an associative list, with their salaries as the value.

  • “$variable name...” is the variable's name, “['key name']” is the element's access index number, and “value” is the array element's value.
  • Let's say you have a group of people and you want to assign gender to each of them based on their names.
  • To do so, you can use an associative list.
  • The code below will assist you in doing so.

Example:

<?php   

/* First method to create an associative array. */

$student_one = array("Maths"=>95, "Physics"=>90,  

                  "Chemistry"=>96, "English"=>93,  

                  "Computer"=>98); 

/* Second method to create an associative array. */

$student_two["Maths"] = 95; 

$student_two["Physics"] = 90; 

$student_two["Chemistry"] = 96; 

$student_two["English"] = 93; 

$student_two["Computer"] = 98;   

/* Accessing the elements directly */

echo "Marks for student one is:\n"; 

echo "Maths:" . $student_two["Maths"], "\n"; 

echo "Physics:" . $student_two["Physics"], "\n"; 

echo "Chemistry:" . $student_two["Chemistry"], "\n"; 

echo "English:" . $student_one["English"], "\n"; 

echo "Computer:" . $student_one["Computer"], "\n"; 

Output: 

Associative_Array_PHP_1

Traversing the Associative Array

Loops are used to traverse Associative arrays in PHP. There are two ways to loop around the associative array. First, by using the for loop, and then by using the ‘foreach’ command.

Example: In Associative arrays in PHP, the array keys() function is used to find indices with names provided to them, and the count() function is used to count the number of indices.

Example

<?php  

/* Creating an associative array */

$student_one = array("Maths"=>95, "Physics"=>90,  

                  "Chemistry"=>96, "English"=>93,  

                  "Computer"=>98);   

/* Looping through an array using foreach */

echo "Looping using foreach: \n"; 

foreach ($student_one as $subject => $marks){ 

    echo "Student one got ".$marks." in ".$subject."\n"; 

/* Looping through an array using for */

echo "\nLooping using for: \n"; 

$subject = array_keys($student_one); 

$marks = count($student_one);      

for($i=0; $i < $marks; ++$i) { 

    echo $subject[$i] . ' ' . $student_one[$subject[$i]] . "\n"; 

?> 

Output

Associative_Array_PHP_2.

Add Another Star to Your Performance Evaluation

Learn from industry experts for FREEStart Learning
Add Another Star to Your Performance Evaluation

Example 2: 

<?php   

/* Creating an associative array of mixed types */

$arr["xyz"] = 95; 

$arr[100] = "abc"; 

$arr[11.25] = 100; 

$arr["abc"] = "pqr";   

/* Looping through an array using foreach */

foreach ($arr as $key => $val){ 

    echo $key."==>".$val."\n"; 

}  

?> 

Output

Associative_Array_PHP_3

Looking forward to becoming a PHP Developer? Then get certified with the PHP Training Course. Enroll now!

Conclusion

An associative array in PHP represents an ordered map. A map is a data form that associates keys with values. This form is well-suited to a variety of tasks; it can be used as an array, list (vector), a hash table (a map implementation), dictionary, set, stack, queue, and possibly more. 

Trees and multidimensional associative arrays in PHP are also possible since array values may be other arrays. Although it is beyond the reach, this Simplilearn course will help you to explain each of these data structures, at least one example is given for each of them.

Do you have any questions regarding this article? Leave your questions or/and inputs for us on the associative array in PHP in the comments section of this page, and our experts will get back to you at the earliest.

Happy learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.