Created
November 11, 2020 17:39
-
-
Save reduardo7/c3abf98f82362e91be2e803d8e2f8d1c to your computer and use it in GitHub Desktop.
PHP - Get object/array value by path.
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 | |
/** | |
* Get array value by path. | |
* | |
* @param string|array $path Array Path. | |
* @param mixed $data Data where search. | |
* @param mixed|null $default Default value on path not found. | |
* @return mixed|null Value. | |
* @see https://stackoverflow.com/a/27930028/717267 | |
*/ | |
function getByPath($path, $data, $default = null) | |
{ | |
if (!$data) { | |
// If no-data, return $default value. | |
return $default; | |
} | |
if (!is_array($path)) { | |
// Split path into Array | |
$path = explode('.', $path); | |
} | |
if (!is_array($data)) { | |
// Convert $data to Array | |
$data = json_decode(json_encode($data), true); | |
} | |
$temp = &$data; | |
foreach ($path as $key) { | |
if (is_array($temp)) { | |
// Go to path key | |
$temp = &$temp[$key]; | |
} else { | |
// Can not get the path | |
return $default; | |
} | |
} | |
// Path result | |
return $temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment