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']);
1
  • The second version won't result in notice. Which you probably have turned off if you are asking this, so please enable them. Commented May 30, 2012 at 19:56

3 Answers 3

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

Comments

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'.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.