Dot notation array access in PHP

Javascript has a nice piece of syntactic sugar of allowing array variables to be access using ".", so that the value myArr[key1][key2] can be accessed through myArr.key1.key2 This is a lot easier to type than the first representation that is similar to what PHP would use. In addition to the square brackets PHP also likes to trigger errors when an array key is not found and one tries to access it. This problem is magnified in Cake PHP where nested arrays are all the rage, especially when generating form inputs.

In an attempt to solve the problem I wrote the following function. In my Cake PHP install for Passbook I placed it in APP/config/bootstrap.php so that it is available everywhere.

// Dot notation array access
function dot(&$arr, $path = null, $checkEmpty = true, $emptyResponse = false) {
// Check path
if (!$path) user_error("Missing array path for array", E_USER_WARNING);

// Vars
$pathElements = split("\.", $path);
$path =& $arr;

// Go through path elements
foreach ($pathElements as $e) {
// Check set
if (!isset($path[$e])) return $emptyResponse;

// Check empty
if ($checkEmpty and empty($path[$e])) return $emptyResponse;

// Update path
$path =& $path[$e];

// Everything checked out, return value
return $path;

To use this function using the previous example one would simply call dot($myArr, 'key1.key2') The parameter checkEmpty allows you to specify whether you want to check if the variable is empty or not, if not the value will be returned as long as it is set. The parameter emptyResponse lets you specify what to return if the is not found or found to be empty.


Post a Comment