Traps of Associative Arrays in PHP

Sead Alispahic
The Apps Team
Published in
2 min readJul 9, 2019

<?php
/*
* Traps of Associative Arrays in PHP
* I was tasked with doing some work in PHP. I’ve used PHP about 15 years ago, so I was not that afraid of diving in. PHP is a great language with great capabilities,
* but it offers something not inherently bad, but in PHP world misused badly. Namely, associative arrays.
*
* For uninitiated, associative arrays are like dictionaries in C# or Maps in JAVA. It is a key-value structure, where items on the left are the names,
* and items on the right are values. Something like:

*/
$arr = array(
“propertyOne”=> 10,
“propertyTwo”=> “some name”
);
/*
* Most PHP developer would then use it like:
*/

echo $arr[“propertyOne”];
echo “<br/>”;
echo $arr[“propertyTwo”];

echo “<hr>”;

/*
* I think that in almost every case of using associative array one shold be using an object.
*
* One of only few valid reasons of using associative array is if you have a number of items in memory and you need to use them based on whatever. For example, I would like to
* format string. Here is what I mean. We will pass the string and tell the formater what to do. We need to have an interface for “formatters”
*/

interface Formatter{
public function format($stringToFormat);
}

/*
* So far so good. We wold then have to create several classes that implement this interface and that would format a string passed in. For example:
*/

class Bold implements Formatter{
function format($stringToFormat){
return “<b>” . $stringToFormat . “</b>”;
}
}

class Italics implements Formatter{
function format($stringToFormat){
return “<i>” . $stringToFormat . “</i>”;
}
}

/*
* Now we need to make this easy to call. We need another class that would hold these in, and we will use associative array
*/

class StringFormatter{
private $formats = array();

function __construct(){
$this->formats[“bold”] = new Bold();
$this->formats[“italics”] = new Italics();
}

function getFormat($formatType){
return $this->formats[$formatType];
}
}

/*
* Now we can call this baby whenever we need it
*/

$formatType = “bold”;
$toFormat = “Hello”;

$stringFormater = new StringFormatter();
$daisyChain = $stringFormater->getFormat($formatType)->format($toFormat);
echo $daisyChain;

/*
* In my opinion this is one of very few valid usecases for associative array. To see this code in action, copy paste the article and run it.
*
* Now, I know I used deprecated tags, that was for a reason. Go, refactor this to use “strong” and “em” and then go, refactor this to use CSS styling.
* See, it is much easier if you do it like this than any other way.
*/
?>

--

--