Afficher un message
Vieux 13/12/2007, 04h40   #5
Norman Peelman
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Simple quote with variable question

Mike wrote:
> I am trying to find the documentation on how and why "id" is quoted in
> the first example, but not in the second.
>
> .............elseif($_GET['id'] == 'pro')............
>
> ............."http://www.xxx.xxx.edu/~xxx/app_upd_2.php?id=
> $_GET[id]&key=$_GET[key]";............
>
> I found this, but it doesnt really tell me why the first id HAS to
> have single qoutes and the second CAN'T:
> When a string is specified in double quotes or with heredoc, variables
> are parsed within it.
>
> I'm just looking for the official explanation.
> Thanks
> Mike


When inside double quotes, PHP doesn't look for defined constants so
you don't need to enclose associative array keys in quotes... unless you
bracket them:

--code--

error-reporting(E_ALL); // everyone knows this constant so we'll use it.

$arr['E_ALL'] = 'world'; // array key is 'E_ALL' not E_ALL
echo "Hello $arr[E_ALL].<br>"; // no errors - PHP does not confuse them.

echo "Hello {$arr['E_ALL']}.<br>"; // no errors - PHP does not confuse them.

echo "Hello {$arr[E_ALL]}.<br>"; // now errors - PHP assumes the defined
constant.

echo "Hello ".$arr[E_ALL]."<br>"; // now errors - PHP assumes the
defined constant.

--end code--

In example #1 the array key name is technically already quoted by the
double quotes (in which php scans for variables) so quotes are not
needed.PHP does not look for defined constants while inside double quotes.
In example #2, the array variable has been isolated with brackets
(which tells PHP to resolve the variable as if it were not in double
quotes and so requires quotes around the key name or PHP assumes the
defined constant.
Examples #3 & #4 show the errors that are thrown when quotes are not
used properly.

It's all in the quotes and brackets:

echo "Hello $arr[E_ALL]";
echo "Hello ".$arr['E_ALL'];
echo "Hello {$arr['E_ALL']}";

....all have the same output.

Also to wrap up, you need to use brackets for multi-dimensional
arrays when inside double quotes:

$arr['cars']['chevy'] = 'Corvette';
echo "MY favorite car is the $arr[cars][chevy].<br>";

....will not have the desired output but (php only sees the first
dimension of the array),

echo "MY favorite car is the {$arr['cars']['chevy']}.<br>";

....does.

---
Norm
  Réponse avec citation
 
Page generated in 0,06079 seconds with 9 queries