douxing8323 2018-05-31 08:45
浏览 71
已采纳

PHP - 当我使用var作为索引时未定义的索引数组

I am getting a strange error when I try to access the array value via key.

This is the array I have:

array:4 [▼
  10 => "mr"
  20 => "ms"
  30 => "mrs"
  40 => "dr"
]

When I try

echo $titles[$user->title]

I am getting Undefined index error, ($user->title can have one of the 4 values from the array keys)

When I try for example

echo $titles[10]

I am getting mr. And when I echo $user->title I am getting 10. Does anyone have an idea what is going on here?

  • 写回答

1条回答 默认 最新

  • dpd66100 2018-05-31 08:48
    关注

    Since such test returned me correct values:

    $titles = [
      10 => "mr",
      20 => "ms",
      30 => "mrs",
      40 => "dr"
    ];
    
    echo $titles[10];
    echo "
    ";
    echo $titles['10'];
    echo "
    ";
    

    I can only guess that You've spaces or invisible symbols in title attribute.

    Fix is simply typecast it that will convert it to integer:

    echo $titles[(int)$user->title]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?