pidari
pidari

Reputation: 459

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?

Upvotes: 0

Views: 61

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

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/>";
}

Upvotes: 1

Related Questions