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?

图片转代码服务由CSDN问答提供 功能建议

当我尝试通过密钥访问数组值时,我收到一个奇怪的错误。 \ n

这是我拥有的数组:

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

当我尝试

  echo $ titles [$ user-> title  ] 
   
 
 

我收到未定义索引错误,( $ user-> title 可以有一个 来自数组键的4个值)

当我尝试示例时

  echo $ titles [10] 
    
 
 

我正在先生。 当我回复 $ user-> title 时,我得到 10 。 是否有人知道这里发生了什么?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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]
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题