Skip to content

Instantly share code, notes, and snippets.

@donnamcmaster
Last active March 3, 2020 00:03
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 donnamcmaster/9d84ffa682df7d9ac3472bfc8fb628ef to your computer and use it in GitHub Desktop.
Save donnamcmaster/9d84ffa682df7d9ac3472bfc8fb628ef to your computer and use it in GitHub Desktop.
PHP utility: find the first non-array element
/**
* First Leaf
* - returns the first non-array element (singular or object).
* - handy when you're not sure whether information has been stored
* as a singular value ('item') or 1-element array (0=>'item').
* - the key() function gives us the first key in the array.
* - uses recursion to go deeper if necessary; if that's not
* what you want, you may need a different solution.
*/
public static function first_leaf ( $value ) {
return !is_array( $value ) ? $value : first_leaf( $value[key($value)] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment