Pages

Thursday, January 14, 2016

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.