5

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!

3 Answers 3

2

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;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this does fix the problem with that particular code snippet, and gives me a little more insight into how this works. Unfortunately, the larger code I originally ran into the problem with still doesn't work... :( I'll keep digging away at it to see if I can make some more progress.
2

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

Comments

0

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

Comments

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.