0

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?

2
  • 2
    What do you get using var_dump($user->title);? Commented May 31, 2018 at 8:56
  • 2
    Make sure $user->title is '10'. I suspect it contains some padding whitespace characters (spaces, newlines etc). Commented May 31, 2018 at 8:56

1 Answer 1

3

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

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.