Skip to content

Instantly share code, notes, and snippets.

@the94air
Last active January 30, 2017 14:22
Show Gist options
  • Save the94air/fd41c7aa3c3e57ece1ef97e88f414ae0 to your computer and use it in GitHub Desktop.
Save the94air/fd41c7aa3c3e57ece1ef97e88f414ae0 to your computer and use it in GitHub Desktop.
Get a value from a multidimensional array using the dot syntax
<?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