6

I am trying to execute this code (it was working on php5, now I'am on php7):

$this->links->$data[$te]['attributes']['ID'] = $data[$te]['attributes']['URL'];

But I get this error:

ContextErrorException: Notice: Array to string conversion

Thanks in advance

6
  • Obviously there is another level below $data[$te]['attributes']['URL'] which contains the actual value and $data[$te]['attributes']['URL'] is an array Commented Oct 9, 2017 at 15:17
  • 1
    what is the value of $te? Commented Oct 9, 2017 at 15:18
  • use var_dump($data[$te]['attributes']['URL']); and check what is in it plz Commented Oct 9, 2017 at 15:20
  • print_r on this->links->$data[$te]['attributes']['ID'] returns the same error. Commented Oct 9, 2017 at 15:22
  • While print_r on $data[$te]['attributes']['URL'] returns a string its value is a link like 'www.google.com' Commented Oct 9, 2017 at 15:22

1 Answer 1

9

This is down to the change in how complex variables are resolved in PHP 5 vs 7. See the section on Changes to variable handling here: http://php.net/manual/en/migration70.incompatible.php

The difference is that the expression:

$this->links->$data[$te]['attributes']['ID']

is evaluated like this in PHP 5:

$this->links->{$data[$te]['attributes']['ID']}

and like this in PHP 7:

($this->links->$data)[$te]['attributes']['ID']

See https://3v4l.org/gB0rQ for a cut-down example.

You'll need to amend your code to be explicit, either by using {} as appropriate, or by breaking it down into two lines. In this case, where you've got code that works fine in PHP 5, pick the former, since it will mean the behaviour stays consistent in all versions of PHP.

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

4 Comments

Hey, Thanks for your reply, but unfortunately it doesnt work: Parse error: syntax error, unexpected '}'
Can you paste what you've changed it to? You probably want to use the second code block in the answer (i.e. change it to explicitly work the PHP 5 way)
Problem resolved by wrapping $data inside {$data[$te]['attributes']['ID']}, as suggested for Php5. The code suggested for PHP7 didn't work. thanks
Ah sorry, I should have been clearer. Both of them are valid in PHP 5 and 7, it's just important that you pick one. If you leave it as the original, then it will behave differently in the two versions. If you have code that's working in PHP 5, then you should use the PHP 5 lines, like you say.

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.