Last active
April 20, 2016 17:35
-
-
Save cdmckay/724fca4ff177ed4aee9b to your computer and use it in GitHub Desktop.
A simple "elvis" operator 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 | |
function elvis($object, $path = null) { | |
return array_reduce(explode('.', $path), function ($subObject, $segment) { | |
return isset($subObject[$segment]) ? $subObject[$segment] : null; | |
}, $object); | |
} | |
// Example | |
$o = [ 'a' => [ 'b' => 1, 'c' => 2 ], 'd' => 3 ]; | |
var_dump(elvis($o, 'a')); | |
// = [ 'b' => 1, 'c' => 2 ] | |
var_dump(elvis($o, 'a.b')) | |
// = 1 | |
var_dump(elvis($o)); | |
// = [ 'a' => [ 'b' => 1, 'c' => 2 ], 'd' => 3 ] | |
var_dump(elvis($o, 'x')); | |
// = null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isset($subObject[$segment]) ? $subObject[$segment] : null
is equivalent to$subObject[$segment]
, since isset just checks if something is not null. At least I think.