Using JSON dot notation in php

Sometimes it’s hard…to say goodbye…to php.

–The Bleatles

If you’re making the transition to node.js and schema-less databases, you’re probably blowing a mind-fuse every day as you watch your code just work instead of spending hours constructing mindless php workarounds.  So in the spirit of nostalgia (for those of us who just can’t let go), here’s … another mindless php workaround.  This one allows you to fetch and set variables in an object or array using the notation “foo.bar” rather than [“foo”][“bar”].  Which is pretty awesome if you don’t think about it.  Just remove the slashes in front of the commented out lines to see it in action, and then put them back and include this file in all the places that you’ll use this in the future.

<?php
//$a = array('foo' => array('bar' => array('baz' => 1)));

function setByPath(&$arr, $path, $value) {
 $keys = explode('.', $path);

 while ($key = array_shift($keys)) {
 $arr = &$arr[$key];
 }

 $arr = $value;
}

//setByPath($a,'foo.bar.freak',3);

function fetchByPath(array $a, $path, $default = null)
{
 $current = $a;
 $p = strtok($path, '.');

 while ($p !== false) {
 if (!isset($current[$p])) {
 return $default;
 }
 $current = $current[$p];
 $p = strtok('.');
 }

 return $current;
}

//var_dump(fetchByPath($a, 'foo.bar'));
?>