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,776
  • 5
  • 31
  • 46
beginner
  • 1,770
  • 2
  • 24
  • 46

2 Answers2

-2

Use:

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

Instead of

echo " i wanna print $array['first']";
Maher Abuthraa
  • 16,698
  • 10
  • 75
  • 102
Pradyut Manna
  • 588
  • 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
  • 89,708
  • 20
  • 100
  • 143
Anant Waykar
  • 642
  • 1
  • 5
  • 18