Skip to content

Instantly share code, notes, and snippets.

@tannerhodges
Last active December 30, 2015 03:39
Show Gist options
  • Save tannerhodges/7770902 to your computer and use it in GitHub Desktop.
Save tannerhodges/7770902 to your computer and use it in GitHub Desktop.
Get the property names of an object. Helpful when parsing JSON data or large arrays with an unknown structure.
/**
* Get property names of an object
* @return array Property names, else error message.
*/
function getPropertyNames($object = null)
{
if (!$object) {
return array('getPropertyNames() was passed an empty object.');
}
$properties = array();
foreach ($object as $property => $property_value) {
array_push($properties, $property);
}
return !empty($properties) ? $properties : array('getPropertyNames() found no properties in your ' . getType($object) . '.');
}
@jonfriskics
Copy link

Have you considered always returning an array? That way, you won't need to have extra logic to treat the output, because right now it might be an array or a string.

@tannerhodges
Copy link
Author

@jonfriskics True that.

PS - Why doesn't Github Gist send you notifications when people leave comments? Awfully inconvenient to find this a month later.

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