-2

I'm getting an Undefined variable: key for this

  $key .= $keys[mt_rand(0, count($keys) - 1)];
Kaorix
  • 1
  • `count` accepts array or `countable` object, use `strlen` for strings. – Sahil Gulati May 14 '17 at 03:14
  • If that's the exact message you're seeing then it's because you're attempting to append a value to `$key` which doesn't already exist. – Nathan Dawson May 14 '17 at 03:18
  • *"I'm getting an Undefined variable: key"* - I hope you meant *"I'm getting an Undefined variable: **keys**"* - Otherwise, what you posted doesn't support the question/error. – Funk Forty Niner May 14 '17 at 03:35
  • Please accept the answer if it resolved your issue, https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work. @Fred-ii- No typo here, the concatenation assignment is causing the warning, `$key .= `. – chris85 May 14 '17 at 04:10
  • @chris85 OP posted one line of code and we don't know where `$keys` is used and if there's more code before it and/or after it. Up until that person can post more code to show relevance, I feel the dupe is a valid close or if you can give me another duplicate for this, I'll add on to it. Your answer is very well-explained btw, I just want everyone to get to the bottom of this. A similar situation happened before where the OP didn't post what was needed, and it turned out that the duplicate I had for it, was valid. I just don't you/me/others to fall in the same trap. – Funk Forty Niner May 14 '17 at 12:54
  • @Kaorix is that the only line of code you have? If there is more, you will need to edit your question and add it. You need to respond. – Funk Forty Niner May 14 '17 at 12:58
  • @chris85 This answer in the duplicate seems to cover it http://stackoverflow.com/a/34354209/1415724 and if not, it could be edited in order to cover it and add an additional explanation, or add another community wiki answer. – Funk Forty Niner May 14 '17 at 13:08

1 Answers1

2

The . of the .= is trying to append to a previously existing $key, which you must not have (for example first iteration of a loop). Initialize $key as NULL or empty at the start of your script.

$key = '';
chris85
  • 23,846
  • 7
  • 34
  • 51