Sasha
Sasha

Reputation: 8705

PHP - Undefined index array when I use var for index

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?

Upvotes: 0

Views: 77

Answers (1)

num8er
num8er

Reputation: 19372

Since such test returned me correct values:

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

echo $titles[10];
echo "\n";
echo $titles['10'];
echo "\n";

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]

Upvotes: 3

Related Questions