Skip to content
Advertisement

unable to create object in php and add key/value pair

I am trying to create an object in PHP and add a key value pair consisting of an email address for the key and an empty array for the value. It is not working. Here is what I’ve tried.

$user[0]['email'] = 'abc@gmail.com';
$obj = new stdClass();
$obj[[$user[0]['email']]=[];

I thought this would produce $obj = {abc@gmail.com:[]} but it appears blank

Advertisement

Answer

You have a Parse error: syntax error here:

$obj[[$user[0]['email']]=[];
     ^

However, since it’s an object and not an array, use a property. Curly braces {} needed since it’s not a valid variable name (not recommended):

$user[0]['email'] = 'abc@gmail.com';
$obj = new stdClass();
$obj->{$user[0]['email']}=[];

Or create an array and cast it to an object:

$user[0]['email'] = 'abc@gmail.com';
(object)$obj[$user[0]['email']]=[];

Both yield:

stdClass Object
(
    [abc@gmail.com] => Array
        (
        )

)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement