Skip to content

Instantly share code, notes, and snippets.

@Tomasz-Silpion
Created October 24, 2017 14:36
Show Gist options
  • Save Tomasz-Silpion/326d766fd2475559f9468cdb8a16bf6b to your computer and use it in GitHub Desktop.
Save Tomasz-Silpion/326d766fd2475559f9468cdb8a16bf6b to your computer and use it in GitHub Desktop.
Get element from multidimensional array by path in php
<?php
/**
* @author Silpion <tomasz@silpion.com.pl>
*/
class Config {
protected $config = [
'a' => [
'b' => [
'c' => 'ok'
]
],
];
/**
* Get element from multidimensional array by path
*
* @param string $path
* @return string
*/
public function get($path)
{
$current = &$this->config;
foreach (explode('/', $path) as $key) {
$current = &$current[$key];
}
return $current;
}
}
$config = new Config;
echo $config->get('a/b/c');
echo $config->get('a/b/e');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment