I'm having an issue with displaying object properties.
normally you would call them using :
$obj["name"]
but what if you did not know the properties e.g "name"
for an array , you can simply call $arr[0] , $arr[1] etc...
But if i have this object (print_r
):
stdClass Object ( [id] => 1 [Name] => george [Number] => 437439742 [Email] => hds@gmail.com)
stdClass Object ( [id] => 2 [Name] => tom [Number] => 4343554643 [Email] => fdhk@gmail.com)
how can i use a foreach to display all the values e.g : 1 , george , 437...
-Without knowing the name of the properties -> NOT $o["id"];
foreach($object as $o)
{
echo $o[i]; // doesn't work on objects
}
I tried converting it to arrays , but it will be an array of the objects so i can;t get the inside info.
//$array = array ($object);
You have a couple of options. One is the get_object_vars()
function, and another is to cast the object to an array.
foreach (get_object_vars($object) as $var => $val) {
// ...
}
or
foreach ((array) $object as $var => $val) {
// ...
}
You can use:
$array = get_object_vars($obj);