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?

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]