Skip to content

Instantly share code, notes, and snippets.

@absent1706
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save absent1706/d0e3d040855fd387ffd1 to your computer and use it in GitHub Desktop.
Save absent1706/d0e3d040855fd387ffd1 to your computer and use it in GitHub Desktop.
Read and write to property of multidimensional array (property is string var)
function getArrayElement($array, $path, $pathDelimiter = '->')
{
// searching for element
$current_array = &$array;
$keys = explode($pathDelimiter, $path);
foreach ($keys as $key)
{
$current_array = &$current_array[$key];
}
return $current_array;
}
function setArrayElement(&$array, $path, $value, $pathDelimiter = '->')
{
// searching for element
$current_array = &$array;
$keys = explode($pathDelimiter, $path);
foreach ($keys as $key)
{
$current_array = &$current_array[$key];
}
$current_array = $value;
}
@absent1706
Copy link
Author

This 2 functions can get ot set array element by path.

Usage example:

array( 'b' => 'val1', 'c' => 'val2' ), 'd' => array( 'e' => 'val3', 'f' => 'val4' ) ); print_r($test_arr); echo "\n"; print_r(getArrayElement($test_arr,'a->b')); echo "\n"; setArrayElement($test_arr,'a->c', 'ololo'); setArrayElement($test_arr,'b', array('1'=>2)); print_r($test_arr);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment