4

I have some little confusion. I want to access the array as follows.

$_POST['un'];

or

  $arr['empno'];

But when I try in double quotes, it gives out a compile time error I tried the following:

 echo "welcome $_POST['un']";

in un i saved username by query string which is out of this question i think.. .so i write welcome i also tried

    echo "$array['emp']";

it also gives me an error. Whats the problem?

André Ferraz
  • 1,511
  • 11
  • 29
Davinder kumar
  • 147
  • 2
  • 11

3 Answers3

2

When using double quotes in php strings you are telling php to interpret the string before printing it.
When using (associative) arrays or methods, you need to use the {} brackets around the value to make it work.

Simple variants, indexed arrays, etc. can be parsed by just using the double quotes, but when using associative arrays and methods, you will need the bracers.

More (and more in depth) info here: Php docs (strings)

echo "Some text... $array['key']";   // Bad
echo "Some text... {$array['key']}"; // Good
echo "Calling $var (simple) and {$var} (complex) is basically the same.";

If you want to do the 'cheapest' type, double quotes is not the way to go, rather go with concatenation and single quotes:

echo 'Some text... ' . $array['key'];
Jite
  • 5,761
  • 2
  • 23
  • 37
  • Even the [php docs in depth](https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing) don't explain at all, why `echo "$array['key']"` is bad. – user31782 Nov 27 '21 at 17:57
  • Well, it's not "bad", it just doesn't work :P – Jite Dec 04 '21 at 18:53
  • Others are suggesting it does work, here: https://stackoverflow.com/a/70137669/3429430 – user31782 Dec 05 '21 at 09:50
  • No, in those cases they don't use any ' or " at all in the array accessor. Seems like that works as well. Personally, I use { } around all variables, makes it cleaner and easier to read imho. – Jite Dec 05 '21 at 17:53
1

Further adding to Fred's comment, if you would like to use array variable, you can use it like:

echo "welcome $_POST[un]";

This will output the value of array variable

André Ferraz
  • 1,511
  • 11
  • 29
hemant
  • 155
  • 1
  • 10
0

Enclose the references to the array with { and }

echo "welcome {$_POST['un']}";

and

echo "{$array['emp']}";
Outspaced
  • 408
  • 5
  • 15