Last active
March 3, 2020 00:03
-
-
Save donnamcmaster/9d84ffa682df7d9ac3472bfc8fb628ef to your computer and use it in GitHub Desktop.
PHP utility: find the first non-array element
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
/** | |
* 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