Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP "Warning: Illegal offset type in ..." array issues have me stumped

I've been having considerable trouble trying to figure out why my arrays weren't working as expected. I was using code functionally the same as the code below, but it was silently failing on me in my program, so I wrote an isolated test case using the same types of data and syntax and got the 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

Those refer to the two lines containing the reference to "$questions[$question]" specifically.

<?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 beyond my skill level here, because while I can see the warning on http://php.net/manual/en/language.types.array.php that states "Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.", I cannot see how what I'm doing is any different than Example #7 on that very page.

I would greatly appreciate an explanation that would help me understand and solve my problem here.

Thank you in advance!

like image 763
Justin Stressman Avatar asked Oct 14 '22 19:10

Justin Stressman


1 Answers

When you call $question = $questions["訓読み: 立"];, you are receiving the array represented by that string. When you use $questions[$question], you should just be using $question:

<?php
    $questions = array(
      "訓読み: 玉"=>array("たま","だま"),
      "訓読み: 立"=>array("たて","たち","たつ","たてる","だてる","だて"),
    );

    $question = $questions["訓読み: 立"];

    if (is_array($question)){
        $res = $question[0];
    } else {
        $res = $question;
    }
    echo $res;
?>
like image 168
ughoavgfhw Avatar answered Nov 15 '22 07:11

ughoavgfhw