Skip to content

Instantly share code, notes, and snippets.

@volter9
Last active August 29, 2015 14:04
Show Gist options
  • Save volter9/e8568303a09716e72039 to your computer and use it in GitHub Desktop.
Save volter9/e8568303a09716e72039 to your computer and use it in GitHub Desktop.
Two functions to manipulate multi-dimensional arrays
<?php
/**
* Two functions to work with multidimensional arrays.
* md_get to get array value using key separated by '.'
* md_set to set array value using key separated by '.'
* Easy, huh?
*
* @author volter9
*/
// Functions
function md_get ($key, $array) {
$keys = explode('.', $key);
while ( is_array($array) ) {
$key = array_shift($keys);
$array = $array[$key];
}
return $array;
}
function md_set ($key, $value, &$array) {
$keys = explode('.', $key);
$temp = $array;
$curs = &$temp;
while ( is_array($curs) ) {
$key = array_shift($keys);
$curs = &$curs[$key];
}
$curs = $value;
$array = $temp;
}
// Example
$c = array (
'friend' => array (
'peter' => 'Hi!',
'james' => 'Hello!'
)
);
// That's how real men work with arrays :D
md_set('friend.james', 'What\'s up?', $c);
print md_get('friend.james', $c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment