Priti's Technical Corner

March 21, 2013

PHP Array Index and Constant

Filed under: PHP, PHP 5.3 Certification, PHP Array — Tags: — pritisolanki @ 5:30 am

I asked following question in my training to explain some point.

Consider following

define(‘Message’,’name’);

$arr[1]=’Hello’;
$arr[‘Message’]=’World’;
$arr[‘name’]=”Jhon”;

echo $arr[1].$arr[Message];

Answers Received :

Hello World
Hello name
Hello Jhon

One question and multiple answers ! The right answer is “Hello Jhon” . Does it tickle your brain? why ! .

Please notice there is no single quote around string index – “Message” in $arr[Message] . And, “Message” is a defined constant which is initialized to “name” and $arr[‘name’] is Jhon :).

Above example explains why we should always provide single quotes to string index.

 

 

 

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: