0

I have an array

$array = ['first'=>'hi','second'=>'bye'];

Why following syntax is not working

 echo " i wanna print $array['first']";

The error message is

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in

But when I tried

 echo "i wanna print $array[first]";

did work fine.

So can someone explain what difference single quotes (') making here. And what does above error really mean, any ideas?

Reporter
  • 3,897
  • 5
  • 33
  • 47
beginner
  • 2,366
  • 4
  • 29
  • 53

2 Answers2

-2

Use:

echo "i wanna print ".$array['first'];

Instead of

echo " i wanna print $array['first']";
Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
Pradyut Manna
  • 588
  • 1
  • 3
  • 12
-2

here php will not able to parse the multi dimension array from double quote string, to acheive same functionality you have to enquote the array variable inside {} brackets.

Try below line of code it will work without error.

echo " i wanna print {$array['first']}";

I hope this help you in understanding.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Anant Waykar
  • 662
  • 2
  • 8
  • 18