pidari pidari - 3 years ago 174
PHP Question

Printing object properties with foreach

I have an anonymous object with 10 properties and I need to print them in the following format: {name}->{value)

This is my code:

$obj = new stdClass();

$obj->name = "Penka";
$obj->age = "25";
$obj->city = "Sofia";
$obj->street = "Hadji Dimitar street";
$obj->occupation = "PHP developer";
$obj->children = 1;
$obj->married = false;
$obj->divorced = true;
$obj->salary = 1300;
$obj->car = "Nissan Micra";

foreach($obj as $data)
{
echo key($obj).' -> '.$data.'<br/>';
}


I don't know how to output the key but I found this function
key()
and it somewhat working but the output is distorted.

age -> Penka
city -> 25
street -> Sofia
occupation -> Hadji Dimitar street
children -> PHP developer
married -> 1
divorced ->
salary -> 1
car -> 1300
-> Nissan Micra


The property
name
is missing and everything is 1 key behind. Why is this happening?

Answer Source

foreach has already advanced the pointer by the time you use the key() function, so it is ahead by one. Just expose the key in the foreach:

foreach($obj as $key => $data)
{
    echo "$key -> $data <br/>";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download