PHP Print keys from an object?

I have a BIRD object, and then there is [0] - [10], and each number has a subtitle, for example, "error" or "bug" or "gnat", and a value for each of them.

I want to print

BIRD [0] bug = > value 

I can’t find out how to do it anywhere - there is talk about PUBLIC, PRIVATE and CLASS and about where I fall

+16
source share
4 answers

I could be wrong, but try to use array_keys , using the object as a parameter. I believe this is possible in php. http://php.net/manual/en/function.array-keys.php

In any case, read about reflection.

+1
source

You can easily do this by pointing the type of object:

$keys = array_keys((array)$BIRD);

+55
source

Like the brenjt request, it uses the PHP get_object_vars instead of typing an object.

 $array = get_object_vars($object); $properties = array_keys($array); 
+25
source

If the β€œobject” is actually an associative array and not a true object, then array_keys() will give you what you need without warning or error.

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

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

 $keysFromObject = array_keys(get_object_vars($anObject)); 
0
source

All Articles