PHP "Warning: invalid offset type in ..." array problems puzzled me

I am having serious problems trying to figure out why my arrays are not working properly. I used the code functionally in the same way as the code below, but it didn’t work in my program, so I wrote an isolated test case using the same data and syntax types and got errors about illegal offset types.

Warning: Illegal offset type in <file location>\example.php on line 12 Warning: Illegal offset type in <file location>\example.php on line 16 

They relate to two lines containing a link to "$ questions [$ question]".

 <?php $questions = array( "訓読み: 玉"=>array("たま","だま"), "訓読み: 立"=>array("たて","たち","たつ","たてる","だてる","だて"), ); $question = $questions["訓読み: 立"]; if (is_array($questions[$question])){ $res = $questions[$question][0]; } else { $res = $questions[$question]; } echo $res; ?> 

I think I'm just above my skill level because for now I see a warning http://php.net/manual/en/language.types.array.php that says: "Arrays and objects cannot be used as keys. As a result, this will result in a warning: type of illegal offset. " I do not see how what I am doing is different from example # 7 on this very page.

I am very grateful for the explanation that will help me understand and solve my problem here.

Thank you in advance!

+4
source share
3 answers

When you call $question = $questions["訓読み: 立"]; , you get the array represented by this string. When you use $ questions [$ question], you should just use $ question:

 <?php $questions = array( "訓読み: 玉"=>array("たま","だま"), "訓読み: 立"=>array("たて","たち","たつ","たてる","だてる","だて"), ); $question = $questions["訓読み: 立"]; if (is_array($question)){ $res = $question[0]; } else { $res = $question; } echo $res; ?> 
+2
source

to get rid of the warning, you should do an extra check before calling is_array with array_key_exists
it should look something like this:

 if (array_key_exists($question,$questions) && is_array($questions[$question])) 

he must complete the task

+1
source

They do not do this on the manual page, as far as I can see. You cannot use arrays as keys.

0
source

Source: https://habr.com/ru/post/1332566/


All Articles