2

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.