Skip to content
Advertisement

How can I use key value of foreach as property value of an object?

I want to print all the properties from an object.

Is there a way to use the key value as a property value of a object? instead of using get_object_vars.

Error

Undefined property: stdClass::$key

Update Example

foreach ($arrayOfArrays as $key => $arrayOfValues) {
   foreach($arrayOfValue as $key => $value){
      $object = (object) $value;
      echo $object->$key;
    }
}

Example of $arrayOfValues

Array
(
    [key1] => "value1"
    [key2] => "value2"
)

Example of $value

stdClass Object
(
    [scalar] => "value1"
)

stdClass Object
(
    [scalar] => "value2"
)

Advertisement

Answer

I think that in your case it was a simple typo:

$arrayOfArrays = [[
    'key1' => 'value 1',
    'key2' => 'value 2',
]];

foreach ($arrayOfArrays as $key => $arrayOfValues) {
    $object = (object) $arrayOfValues;
    echo $object->key1; // you ommited the 1;
}

As the other mentioned you can use directly the array. No need to convert it to object:

foreach ($arrayOfArrays as $key => $arrayOfValues) {
    echo $arrayOfValues['key1'];
}

If you want to display all the keys of that array you can simply use something like:

foreach ($arrayOfArrays as $key => $arrayOfValues) {
    $object = (object) $arrayOfValues;

    foreach (array_keys($arrayOfValues) as $unkownKey) {
        echo $object->$unkownKey;
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement