Sandeep Chayapathi <something or the other>

Key-Value-Coding in PHP

Objective-C provides a very concise way of accessing values of any object (that supports NSKeyValueCoding protocol).

Here’s my attempt at implementing a simple KVC type accessor for PHP arrays.

/**
 * value_for_keypath
 *
 * returns value at the given key path in an multi-dimensional array (map)
 *
 * @param $array
 * @param $path string , each path element is separted by a dot (.)
 */
function value_for_keypath($input, $path)
{
	$keys = explode( ".", $path );
	$tmp_val = $input;

	foreach ($keys as $key) {
		if (isset( $tmp_val[$key] )) {
			$tmp_val = $tmp_val[$key];
		} else {
			return null;
		}
	}

	return $tmp_val;
}

Eg:

php > $a = array('a' => array('b' => array('c' => 'test')));
php > echo value_for_keypath($a , "a.b.c");
test

Note: PHP is a very forgiving language, one can access non-existent keys in a deeply nested multi-dimensional array and at runtime only a notice is generated, eg:

php > $a = array('a' => array('b' => array('c' => 'test')));
php > echo $a['a']['b']['d'];
PHP Notice:  Undefined index: d in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0