Skip to content

Instantly share code, notes, and snippets.

@cdmckay
Last active April 20, 2016 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdmckay/724fca4ff177ed4aee9b to your computer and use it in GitHub Desktop.
Save cdmckay/724fca4ff177ed4aee9b to your computer and use it in GitHub Desktop.
A simple "elvis" operator in PHP
<?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
@emanb29
Copy link

emanb29 commented Apr 20, 2016

isset($subObject[$segment]) ? $subObject[$segment] : null is equivalent to $subObject[$segment], since isset just checks if something is not null. At least I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment