Skip to content
PHP Logo

What is the significance of using quotes around array index string literals in PHP?

When accessing array elements using string literals as indexes in PHP, it is important to use quotes around the index to ensure that the string is treated as a key and not a constant. Without the quotes, PHP will try to interpret the string as a constant, which may lead to unexpected results or errors. By using quotes, we explicitly tell PHP to treat the string as a key in the array.

php
// Incorrect way without quotes
$array = ['key' => 'value'];
echo $array[key]; // This will throw a notice about undefined constant

// Correct way with quotes
$array = ['key' => 'value'];
echo $array['key']; // This will output 'value'