Monday 20 November 2017

php - Why I'm getting parse error in accessing an array value present under the key of string type?

itemprop="text">



I have tried
following code
:



 $juices =
array("apple", "orange", "koolaid1" => "purple");

// For below
line of code I get tis error : Parse error: syntax error, unexpected ''
(T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable
(T_VARIABLE) or number (T_NUM_STRING)

echo "He drank some
$juices['koolaid1'] juice.".PHP_EOL;

// For below line of code too
I get tis error : Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE),
expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number
(T_NUM_STRING)
echo "He drank some $juices["koolaid1"]
juice.".PHP_EOL;

//Below line of code works fine. Prints He drank
some purple juice.
echo "He drank some $juices[koolaid1]
juice.".PHP_EOL;
?>



My
question is as the type of key I'm accessing is string then
I should have to put it inside single or double quotes to get access to the value it
holds. I'm doing the same thing here but getting a parse error. Why this is
happening?



And on the other hand it's really
very surprising to see that when I don't make use of single or double quotes around the
key of string type it's working
fine.



I got totally confused here due to this
strange behavior of PHP. Please someone provide me useful
help.



Answer




When your array variable is already in double
quotes " at that time you don't have to add any quotes for
accessing index. You just have to directly write index name without any quotation. But
If you don't have any quotes around array at that time you have to add quotation for
accessing string index.



echo "He
drank some $juices[koolaid] juice.".PHP_EOL;
//No need any
quotation




echo
$juices['koolaid'];
//Need quotation here



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...