Home php Illegal offset type - what's the problem?

Illegal offset type – what’s the problem?




Good afternoon. I form JS with this expression:

for ($ i = 0; $ i & lt; (count ($ configNames)); $ i ++) {
echo "$ ('#". $ configNames [$ i]. "'). text ('". $ config [$ configNames [$ i]]. "');";}

In response, I get swear words like “Illegal offset type”, but the script itself is executed as it should. What is the racially correct option to use as a substitute in order to avoid swearing?

Thank you all for your answers. The variant with the use of an additional variable removed the curses, but settled on the variant with the foreach loop, since, apparently, it is more canonical.

Answer 1, authority 100%

Obviously, the $ config array is nested, and its elements can be both scalars and other arrays.
As a consequence, apparently, $ configNames also has a hierarchical structure, although I would not do that.

foreach ($ configNames as $ name)
  if (! is_array ($ name))
    echo "$ ('# $ name'). text ('$ config [$ name]');";

Plus, I basically don’t understand why there is a separate $ configNames array here.
If it does not serve to filter certain elements, but exactly contains the keys of the $ config array, then in principle it is not needed:

foreach ($ config as $ name = & gt; $ value)
  if (is_scalar ($ value))
    echo "$ ('# $ name'). text ('$ value');";

but both of these codes will skip nested arrays. If they also need to be passed to JS, then a recursive function will be needed

Answer 2, authority 50%

Complementing the rest of the answers.

The first thing you shouldn’t do is generate javascript dynamically. You don’t see the end result , it’s easy to make a mistake. Pass the data as a JSON string in one way or another (window.pageData = & lt;? Php echo json_encoode ($ data);? & Gt; or via data attributes).

Second, you have a complex and non-obvious data structure, which is why these errors occur. You cannot peer inside the code without a debugger, and this makes debugging very difficult.

Answer 3

Try this:

for ($ i = 0; $ i & lt; (count ($ configNames)); $ i ++) {
  $ name = $ configNames [$ i];
  echo "$ ('#". $ name. "'). text ('". $ config [$ name]. "');";

Besides, I think in this case it will be clearer to use the loop foreach .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions