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/>';
}
key()
age -> Penka
city -> 25
street -> Sofia
occupation -> Hadji Dimitar street
children -> PHP developer
married -> 1
divorced ->
salary -> 1
car -> 1300
-> Nissan Micra
name
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/>";
}