What is a PHP Associative Array Hash Map: 5 Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Using associative array hash maps in PHP

Before seeing an associative array or hash map in PHP, let’s first learn some generic data structures.

Array

An array is a standard data structure in programming. Unlike a variable, an array can store many values of the same or mixed data types. Every programming language features the array data structure at its core, with slight modifications. For instance, typically, Java does not allow mixed data types in an array, but PHP and Javascript do.

associative array or hash map in PHP

Hash maps also store many values but go an extra mile. How so?

Hash Map

Similarly, a hash map is a data structure that associates a unique identifier to a value. In more precise terms, it keeps “KEY-VALUE” pairs. The key and the value can have the same or different data types. These keys are meant for accessing the values. In the case of an array, every programming language has a different implementation for the hash map.

associative array or hash map in PHP

C++ term it unordered map, Python dictionary, and associative array in PHP.

Associative array or hash map in PHP

PHP has built-in support for associative arrays. That means it does not need any imports from external libraries or third parties. You can initialize an array by using the array() keyword or just placing comma-separated key and value pairs in [ ] brackets. The key and value pair is defined this way, key => value. 

//Initializes an array using [] syntax
$array = [
    "Key1" => 'Hi',
         2 =>  'Good Morning',
       2.2 => 2927,
     "Bye" => 2.224
 ];
 
 //OR
 
 
//Initializes an array using array() syntax
 $array = array(
    "Key1" => 'Hi',
         2 =>  'Good Morning',
       2.2 => 2927,
     "Bye" => 2.224
 );

So, an associative array in PHP is a way to go if there’s a need to store data related to, let’s say, students and their quiz marks. That’s because the student name could be the key, and the quiz marks could be the value. This setting will be more intuitive and offers ease of accessing the data using the student name as an index. Can you think of another such example?

$students = [
    "Anderson" => 12,
    "Brian" => 10,
    "Cristina" => 13,
    "Daniel" => 18,
    "Eisha" => 15,
    "Franklin" => 15,
    "Gina" => 8,
    "Haytham" => 19,
    "Isaac" => 14,
    "Jenny" => 10,
    "Kevin" => 16,
    "Liam" => 8,
    "Mona" => 5,
    "Neha" => 15,
    "Orban" => 12,
    "Peter" => 17,
    "Richard" => 11,
    "Stacie" => 12
];

We can do a bunch of things with associative array PHP. PHP features many useful functions for different array operations, manipulations, and transformations. FuelingPHP has tons of articles covering array functions and tutorials for associative array in PHP. 

Associative array or hash map in PHP: Rewind Time

Let’s glance over some essential things related to the associative array or hash map in PHP. If a particular topic intrigues you, do not shy away from learning it in-depth by following the link to the related article.

How to loop through an associative array in PHP

PHP features several loop constructs to iterate through an array. These loops are :

  • foreach loop
  • for loop
  • while loop
  • do-while loop

The foreach loop is ideal for the PHP associative array because it keeps reference for both keys and variables while looping through an array.

<?php
 
//An array containing employee-age as key-value.
$employee_age = [
    "Peter" => 22,
    "Anna" => 25,
    "Steve"   => 30,
    "Bob"  => 32,
    "Mark" => 35]; 
 
//foreach loop to iterate over the $employee_age array.
foreach($employee_age as $employee => $age)
{
    echo $employee." is ".$age." years old."."\n";
}
 
/*
OUTPUT
Peter is 22 years old.
Anna is 25 years old. 
Steve is 30 years old.
Bob is 32 years old.  
Mark is 35 years old. 
 */
?>

The foreach loop uses $employee to access the employee name key and age for the array’s values.

How to print associative array PHP

There are a few ways to print an associative array to the console. 

  • Using the foreach loop
  • Calling the print_r function
  • The var_dump function
  • Using the echo with implode function

The article explains these in-depth, but we will see the print_r functions that are more convenient and frequently used.

<?php
//An array containing names.
$names_arr = array("John","Stuart","Sophie","Sara","Adam");
 
//Prints an array to the console.
print_r($names_arr);
 
 
/**
 * OUTPUT 
 *  Array
 *   (
 *      [0] => John  
 *      [1] => Stuart
 *      [2] => Sophie
 *      [3] => Sara  
 *      [4] => Adam  
 *   )
 */
?>

How to add to an associative array or hash map in PHP

There are yet again several methods to add to an array in PHP. 

  • The array_push function
  • Using the square bracket function
  • The array_unshift function
  • The array_splice function

Let’s check out how to add to the end of an array using the array_push function.

<?php
 
//Array with three elements.
$fruits = array('Apple','Orange','Mango');
 
//array_push: Adding three elements to the end of the $fruits array.
array_push($fruits,'Watermelon','Avocado','Strawberries');
 
 
//Output the array to console.
print_r($fruits);
 
/*
Array
(
    [0] => Apple       
    [1] => Orange      
    [2] => Mango       
    [3] => Watermelon  
    [4] => Avocado     
    [5] => Strawberries
)
*/
 
?>

How to remove an element from an associative array in PHP

Here are some of the functions for removing array elements.

  • unset
  • array_pop
  • array_shift
  • array_splice

Here’s an example of array_pop.

<?php

$students = [
    "Anderson" => 12,
    "Brian" => 10,
    "Cristina" => 13,
    "Daniel" => 18,
    "Eisha" => 15,
];

print_r(array_pop($students));

//OUTPUT
//15AA

?>

How to sort an associative array or hash map in PHP

PHP features a bunch of functions for sorting.

  • sort() – Sorts an array in ascending order.
  • rsort() – Sorts an array in descending order.
  • asort() – Sorts an associate array by value, in ascending order.
  • arsort() – Sorts an associative array by value, in descending order.
  • ksort() – Sorts an associate array by key, in ascending order.
  • krsort() – Sorts an associate array by key, in descending order.

The article has examples of all these functions. Let’s see the sort function in the example.

<?php 
//Array containing names. 
$names_array = array("Zeus","Tina","Robert","Benjamin","Stacie","Anna","Franklin"); 
//Sort names in ascending order. 
sort($names_array); 
//Print the name array. 
print_r($names_array); 
/* OUTPUT Array ( 
                                   [0] => Anna 
                                   [1] => Benjamin
                                   [2] => Franklin
                                   [3] => Robert 
                                   [4] => Stacie 
                                   [5] => Tina 
                                   [6] => Zeus )
 */
 ?> 

How to get an array length in PHP

An array length is the count of the elements in it. PHP has the count and sizeOf functions to get the length of an associative array. Here’s how the count function works.

<?php
//An array with many elements.
$arr = array("PHP","Javascript","Python","Java","C#","C++");
 
//Let's count this array using the count function and print it to console.
echo "Length of \$arr is: ".count($arr);
 
//OUTPUT
//Length of $arr is: 6
?>

How to convert array to string with PHP implode function

Converting an associative array or hash map in PHP to a string is common in development. PHP has a really excellent function for this conversion, and that is the array_implode. Here’s a quick review of how this function works.

<?php 
//An array to be converted into a string. 
$programmingLanguagesArray = ["PHP","Python","Javascript","Java","C++","R"]; 
//convert $programmingLangugaes array into string using the implode function. $programmingLanguagesString = implode(", ",$programmingLanguagesArray); 
//Echo $programmingLanguagesString to console. 
echo $programmingLanguagesString; 
//OUTPUT //PHP, Python, Javascript, Java, C++, R 
?>

How to split an associative array or hash map in PHP

We have a couple of functions for splitting an array. Let’s check out the array_chunk in an example.

<?php
//An array to be splitted.
$big_array = array("a","b","c","d","e","f","g");
 
//Split array to have elements [a,b,c,d] which means an offset of 0 and length of 4.
$first_split = array_slice($big_array,0,4);
 
//Split array to have elements [e,f,g,h] which mean an offset of 4 and length of 3.
$second_split = array_slice($big_array,4,3);
 
 
/*OUTPUT 
Array       
(
     [0] => a
     [1] => b
     [2] => c
     [3] => d
)
*/
print_r($first_split);
 
 
 
/*OUTPUT
Array       
 (
     [0] => e
     [1] => f
     [2] => g
 )
*/ 
print_r($second_split);
 
?>

How to find and remove duplicate values in PHP arrays

PHP features the array_unique function to remove duplicate array values.

<?php
 
$arr = ["Red","Yellow","Green","White","Red","Pink","Yellow","Black","White"];
 
$arr = array_unique($arr);
 
print_r($arr);
 
/*
OUTPUT
Array
(
    [0] => Red  
    [1] => Yellow
    [2] => Green
    [3] => White
    [5] => Pink  
    [7] => Black
)
*/
?>

Conclusion

This article explains all about associative array or hash map in PHP and reviews some most common array functions. However, this is not the end of the list, as there are many such interesting and helpful articles and tutorials related to PHP at FUELINGPHP.

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to merge 2 arrays with the same keys in PHP

Difference between array_combine and array_merge in PHP

PHP array_search: How to use in PHP with examples

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.