Last active
January 30, 2017 14:22
-
-
Save the94air/fd41c7aa3c3e57ece1ef97e88f414ae0 to your computer and use it in GitHub Desktop.
Get a value from a multidimensional array using the dot syntax
This file contains 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 | |
class Helper | |
{ | |
public static function get( $arr, $key, $default=null ) | |
{ | |
@list( $index, $key ) = explode( '.', $key, 2 ); | |
if ( !isset( $arr[$index] ) ) return $default; | |
if ( strlen( $key ) > 0 ) return static::get( $arr[$index], $key, $default ); | |
return isset( $arr[$index] ) ? $arr[$index] : $default; | |
} | |
} | |
$arr = [ | |
'db' => | |
[ | |
'name' => | |
[ | |
'data' => 'hahaha' | |
] | |
], | |
'age' => '29' | |
]; | |
echo Helper::get( $arr, 'db.name.data' ); echo '<br>'; | |
echo Helper::get( $arr, 'age' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment