Including Array Elements in Double-Quoted Strings in PHP


How Many Ways to Include Array Elements in Double-Quoted Strings?



There are 2 formats to include array elements in double-quoted strings:

  • "part 1 $array[key] part 2" - This is called simple format. In this format, you can not specify the element key in quotes.
  • "part 1 {$array['key']} part 2" - This is called complex format. In this format, the array element expression is specified in the same way as in a normal statement.

Here is a PHP script example of different ways to include variables in double-quoted strings:

$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
echo "A banana is $fruits[banana].\n";
echo "A banana is {$fruits['banana']}.\n";

This script will print:

A banana is yellow.
A banana is yellow.

"A banana is $fruits['banana'].\n" will give you a syntax error.


Accessing a Specific Character in String in PHP

Ways to Include Variables in Double-Quoted Strings in PHP

Understanding PHP String Literals and Operations

⇑⇑ PHP Tutorials

2016-10-13, 1485🔥, 0💬