Justin Stressman
Justin Stressman

Reputation: 51

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!

Upvotes: 5

Views: 15329

Answers (3)

alienn
alienn

Reputation: 223

to get rid of the warn you must do additional check before callind is_array by using array_key_exists
it should look something like that:

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

it should do the job

Upvotes: 2

ughoavgfhw
ughoavgfhw

Reputation: 39905

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;
?>

Upvotes: 2

Jonah
Jonah

Reputation: 10091

They don't do that on the manual page as far as I can see. You can't use arrays as keys.

Upvotes: 0

Related Questions