If I omitted single quotes in $ _variable ['variable']?

Possible duplicate:
Access to arrays without quoting a key

I noticed a subtle difference there ... if I were to code this:

echo "Welcome, $_SESSION['username'], you are logged in.";

This will fail during parsing. However, if the code is:

echo "Welcome, $_SESSION[username], you are logged in.";

This works as expected, which makes me wonder if single quotes are really needed. I cannot find anything in the PHP documentation showing this effect.

+3
source share
6 answers

In PHP, a global constant that is not defined becomes a string .

Do not rely on it ; always quote array keys.

, , , .

Konforce .

, .

, , .

+3

, $_SESSION[username] , .

PHP

. , $foo ['bar'] , $foo [bar] - . , . , undefined (bar), ( "bar" - ).PHP , , , . , PHP ( , ) , . , bar, PHP "bar" .

.

+3

,

Array do and don'ts

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
// 
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
+1

, {} ("...{$array['key']}..." ...$array[key]...). , - "...$foobar...", "...{$foo}bar..." (.. Var $foo, bar).

, , vars , : '...' . $var . '...'

0

, , , . - ​​ . , , . - ?

PHP , , ( " " ).

0

Yes.
If you pass an argument to an array without quotes, php will first try to interpret the argument as a constant, and if it is not defined, it will act as expected. Even if he can give the same result, he is much slower than the argument given.
Here is an example of when this might not work:

define("a_constant","a value");
$a = array("a_constant"=>"the right value");
echo $a[a_constant]; 

The variable a_constanthas a value of "value", so $a[a_constant]it goes into $a["a value"], a key that does not exist in the array $a.

0
source

All Articles