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'] = '[email protected]'; $obj = new stdClass(); $obj[[$user[0]['email']]=[];
I thought this would produce $obj = {[email protected]:[]} 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'] = '[email protected]'; $obj = new stdClass(); $obj->{$user[0]['email']}=[];
Or create an array and cast it to an object:
$user[0]['email'] = '[email protected]'; (object)$obj[$user[0]['email']]=[];
Both yield:
stdClass Object
(
[[email protected]] => Array
(
)
)