Skip to main content

PHP Arrays - Associative Arrays or Hash Maps


Associative array or hash maps are listings of key and value pairs with a posibility to nest additional keys and values. An associative array is a very powerful construct within PHP.

In our previous article we discussed simple arrays, which in their turn are indexed associative arrays under the hood. Take the following example:

$array = [
  
'apple',
  
'banana',
  
'chocolate',
]; 


Is in fact an indexed associative array under the hood:

$array = [
    
=> 'apple',
    
=> 'banana',
    
=> 'chocolate',
]; 


But associative arrays can be so much more than just an indexed array, and you will find many database operations returning arrays where the fields of a table are the keys in the array while their values are also the values within the array.

$productRowData = [
    
'product_id' => 1234,
    
'brand_id' => 321,
    
'product_name' => 'Our awesome product',
    
'prodcut_description' => 'This is our most awesome product.',
    
'product_sku' => 'ABC1234-XYZ',
    
'product_price' => 59.95,
];


Another example of use is to store configuration information in a PHP array, like Zend Framework does. It's maybe why they call it the "Array Framework". But it's actually a good approach to store configuration settings inside a PHP array as you don't need to parse another format like INI, XML, YAML, JSON or CSV, saving a couple of CPU cycles loading the configuration for your application. Once parsed, it will be represented as an array anyways, maybe serialized for persistance.

$dbConfig = [
    
'db' => [
        
'erp' => [
            
'host' => '123.123.456.456',
            
'port' => 3306,
            
'username' => 'erp_user',
            
'password' => 'v3rRy$ecR3tP@ssMor7! ',
            
'dbname' => 'erp',
        ],
        
'crm' => [
            
'host' => '123.123.426.426',
            
'port' => 3306,
            
'username' => 'crm_user',
            
'password' => ' Y0u L1k3 f1&h 4nD Ch1p$?! ',
            
'dbname' => 'crm',
        ],
    ],
];


How can we iterate over these values? The easiest way is to use "foreach()" as we can define the key and value in the iteration construction:

foreach ($productRowData as $key => $value) {
    echo 
'key : '  $key PHP_EOL;
    echo 
'value: ' $value PHP_EOL;
    echo 
PHP_EOL;
}


For the other loops like "for", "do-while" and "while-do" we need to do a bit of extra work. As we don't have direct access to the "index" of the associative array, we cannot iterate over the keys. So we fetch the keys as a seperate array with "array_keys" function.

$count count($productRowData); 
$keys array_keys($productRowData);

echo 
'== Iteration with for' PHP_EOL;
for (
$i 0$i $count$i++) {
    echo 
'key : '  $keys[$i] . PHP_EOL;
    echo 
'value: ' $productRowData[$keys[$i]] . PHP_EOL;
    echo 
PHP_EOL;
}

echo 
'== Iteration with do-while' PHP_EOL
$i 0;
do {
    echo 
'key : '  $keys[$i] . PHP_EOL;
    echo 
'value: ' $productRowData[$keys[$i]] . PHP_EOL;
    echo 
PHP_EOL;
    
$i++;
} while (
$i $count);

echo 
'== Iteration with while-do' PHP_EOL
$i 0;
while (
$i $count) {
    echo 
'key : '  $keys[$i] . PHP_EOL;
    echo 
'value: ' $productRowData[$keys[$i]] . PHP_EOL;
    echo 
PHP_EOL;
    
$i++;
}


Both loops "for" and "while-do" will first evaluate the given condition before they start their iteration. The "do-while" loop will execute the loop at least once before validating a condition. In some conditions this can be convenient.

What if we want to look for a specific value, should we iterate over each element until we find the value? Let's say we are looking in our configuration for the array containing the value "123.123.426.426" because we found it in one of our logs. A very common practice is the following example:

$searchResult null
$search '123.123.426.426'

foreach (
$dbConfig as $db) {
    foreach (
$db as $target => $dbSettings) {
        if (
$search === $dbSettings['host']) {
            
$searchResult $dbSettings;
        }
    }

// do something with $searchResult

This is a very common practice I come accross and even though it's not a bad practice, there are php array functions available that do the trick as well. In this case, I choose "array_filter" to quickly retrieve the correct array.

foreach ($dbConfig as $db) {
    
$searchResult array_filter($db, function ($v) use ($search) {
        return 
in_array($search$v);
    });

// do something with $searchResult

Above functionality allows us to keep a clear understanding what's going on and we reduce the amount of iterations we need to execute. Consider doing this on an array with a couple of 1000 entries.

In our next article we're going to look a bit more at the various PHP array functions you can use in your day-to-day application development.

Comments

Popular posts from this blog

PHP 7 and Apache on macOS Sierra

I posted several talks about compiling PHP from source, but everyone was trying to convince me that a package manager like Homebrew was a more convenient way to install. The purpose of Homebrew is simple: a package manager for macOS that will allow you to set up and install common packages easily and allows you to update frequently using simple commands. I used a clean installation of macOS Sierra to ensure all steps could be recorded and tested. In most cases you already have done work on your Mac, so chances are you can skip a few steps in this tutorial. APACHE AND PHP WITH HOMEBREW I’ve made this according to the installation instructions given on GetGrav. The installation procedures These installation procedures will set up your macOS Sierra with PHP 7.1 and Apache 2.4. Install Xcode command line tools (if not done yet)xcode-select --install Install Homebrew/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Set up for in…

Sessions in PHP 7.1 and Redis

In case you have missed it, PHP 7.1.0 has been released recently. Now you can’t wait to upgrade your servers to the latest and greatest PHP version ever. But hold that thought a second… With PHP 7 lots of things have changed underneath the hood. But these changed features can also put unexpected challenges on your path. Our challenge One of these challenges that we faced was getting PHP 7.1 to play nice storing sessions in our Redis storage. In order to store sessions in Redis, we needed to install the Redis PHP extension that not only provides PHP functions for Redis, but also installs the PHP session handler for Redis. Because we upgraded our servers to PHP 7.1, we were looking to use the latest provided version for this Redis extension: redis-3.1.0. Once installed, we bumped against a nasty problem. Warning: session_start(): Failed to read session data: redis (path: tcp://127.0.0.1:6379) Searching the internet for this error, we didn’t got many hits that could point us into a dire…

VAT Validation now for PHP 7.1+

When I started my European Commission (EC) VAT Information Exchange System (VIES) project back in 2011, PHP 5.3 was the current version that has given us so much. Earlier that year version 5.2 was announced End-of-Life and everyone was excited about the new features in PHP coming with the 5.3.x releases.

But fast-forwarding to today, PHP 7.1 is the latest stable release and PHP 5.6 only gets security fixes until the end of this year. In the mean time several open-source projects like PHPUnitXDebugZend FrameworkLaravelJoomlaTYPO3Magento and Symfony announced they stop development for PHP 5 versions and now only move forward with PHP 7.1 and higher.

After seeing Sebastian Bergmann’s talk PHP 7: Reality Check I was empowered by his reasoning that it’s not worth putting support in outdated PHP versions and focus on the current and future versions that will make a difference in functionality, performance and security.

For this reason I would like to announce that the European …