Created
October 24, 2017 14:36
-
-
Save Tomasz-Silpion/326d766fd2475559f9468cdb8a16bf6b to your computer and use it in GitHub Desktop.
Get element from multidimensional array by path in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Silpion <[email protected]> | |
*/ | |
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