Skip to content

Instantly share code, notes, and snippets.

@zeroasterisk
Created July 6, 2015 14:59
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 zeroasterisk/9a8edfe1df7cb02d1667 to your computer and use it in GitHub Desktop.
Save zeroasterisk/9a8edfe1df7cb02d1667 to your computer and use it in GitHub Desktop.
[KyOSS Discuss] Help with PHP - using values in indexed array to traverse multi-dimensional array
<?php
/**
* pluck out a value from a nested array, based on a $path
* where $path is a single-dim list of keys.
*
* @param array $form (multi-dim)
* @param array $path (single dim)
* @reutrn mixed $value from $form, in $path
*/
function darren($form, $path) {
if (!is_array($form)) {
throw new OutOfBoundsException("First arg should be an array, within which to look");
}
if (!is_array($path)) {
throw new OutOfBoundsException("Second arg should be an array, of the path for");
}
$ref = &$form;
foreach ($path as $key) {
if (!in_array($key, $ref)) {
throw new OutOfBoundsException("Unable to find {$key}");
}
$ref = &$ref[$key];
}
return $ref;
}
// example values to test
$form = [
'a1' => [
'b1' => [
'c1' => [
'd1' => 'value'
]
]
]
];
$path = ['a1', 'b1', 'c1', 'd1'];
$expect = 'value';
echo (darren($form, $path) == $expect ? 'Good' : 'I Hate Life');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment