Reputation: 1629
The following piece of code:
$field = 'field_total_comments_added';
$current_user_count = $user_data->$field['und']['0']['value'];
returns an error: Fatal error: Cannot use string offset as an array
if I just use:
$current_user_count = $user_data->field_total_comments_added['und']['0']['value'];
the code works just fine. In order to use some custom functionality I have to use the variable displayed in the first code block. How can I solve this?
Please tell me if the problem isn't clear to you.
Thanks in advance for your assistance
Upvotes: 2
Views: 293
Reputation: 145482
You can use this common workaround:
$current_user_count = $user_data->{$field}['und']['0']['value'];
Which basically forces the variable property name to have precedence over the array access operator.
Upvotes: 7
Reputation: 7315
Try:
$field = 'field_total_comments_added';
$current_user_count = ($user_data->$field)['und']['0']['value'];
It might only work for PHP 5.4. For earlier versions, also try:
$field = 'field_total_comments_added';
$item = $user_data->$field;
$current_user_count = $item['und']['0']['value'];
Upvotes: 1