0

Possible Duplicate:
Do PHP array keys need to we wrapped in quotes?
Is it okay to use array[key] in PHP?

This is the code I am running and I am wondering whether I should quote the word message with single quotes like the second line of code in this post. Which is best practice?

$post = array('message' => $result[message]);

Or this?

$post = array('message' => $result['message']);
Community
  • 1
  • 1
Somk
  • 11,869
  • 32
  • 97
  • 143
  • The second version won't result in notice. Which you probably have turned off if you are asking this, so please enable them. – Esailija May 30 '12 at 19:56

3 Answers3

3

Do use strings!

Your first example, $post = array('message' => $result[message]);, would not execute the same if "message" were defined as a constant.

Also, with syntax highlighting,

// this
$post = array('message' => $result['message']);
// or this
$post = array('message' => $result["message"]);
// is more readable than this
$post = array('message' => $result[message]);
Deltik
  • 1,129
  • 7
  • 32
0

I'd recommend the quotes for readability. When someone is reading your code, they might think that [message] is a variable, when in reality it's supposed to be a literal string: 'message'.

JMC
  • 910
  • 7
  • 11
0

Incorrect usage if the message constant is undefined or is defined but does not contain the value "message":

$post = array('message' => $result[message]);

Why?

Writing message (without $ sign) means you are accesing a PHP constant. PHP's default behaviour is to issue a notice that the constant is undefined, then convert the undefined constant's name to a value.

oxygen
  • 5,891
  • 6
  • 37
  • 69