31

I have an object BIRD and then there is [0] through [10] and each number has a subheading like "bug" or "beetle" or "gnat" and a value for each of those.

I want to print

BIRD 
    [0]
       bug = > value 

I can't find out how to do this anywhere - there is talk of PUBLIC and PRIVATE and CLASS and that's where I fall off

CharlesB
  • 86,532
  • 28
  • 194
  • 218
user723220
  • 817
  • 3
  • 12
  • 20

4 Answers4

92

You could easily do it by type casting the object:

$keys = array_keys((array)$BIRD);
Soviut
  • 88,194
  • 49
  • 192
  • 260
brenjt
  • 15,997
  • 13
  • 77
  • 118
55

Similar to brenjt's response, this uses PHP's get_object_vars instead of type casting the object.

$array = get_object_vars($object);
$properties = array_keys($array);
nick
  • 3,544
  • 1
  • 26
  • 22
13

If the 'object' is actually an associative array rather than a true object then array_keys() will give you what you need without warnings or errors.

On the other hand, if your object is a true object, then you will get a warning if you try use array_keys() directly.

You can extract the key-value pairs from an object as an associative array with get_object_vars(), you can then get the keys from this with array_keys():

$keysFromObject = array_keys(get_object_vars($anObject));
Bart B
  • 661
  • 8
  • 18
3

Looks like array_keys might have stopped working on objects but, amazingly, the foreach construct works, at least on a php stdClass object.

$object = new stdClass();
$object->a = 20;
$object->b = "hello";
$keys = array_keys($object);
// array_keys returns null. PHP Version 7.3.3 windows
foreach($object as $key=>$value)
{
     // but this works
     echo("key:" . $key . " value:" . $value . "\n");
}