Click to See Complete Forum and Search --> : array --doubt


keerthi
12-21-2005, 10:31 PM
hi

i would like to know how the output differs becos of bracket usage..wt s the main usage of bracket
<?
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
<br>
<?
print $arr[fruit]; // apple
?><br><hr>
<?
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
?>
<br>
<?
print $arr[fruit]; // carrot
?>
<br>
<?
print "Hello $arr[fruit]"; // Hello apple
?><br>
<?
print "Hello {$arr[fruit]}"; // Hello carrot--clarification needed here
?>
<br>
<?
print "Hello $arr[fruit]"; // Hello apple
?>
<br><hr>
<?
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

NogDog
12-21-2005, 10:43 PM
http://www.php.net/manual/en/language.types.array.php#language.types.array.foo-bar
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

keerthi
12-21-2005, 11:26 PM
does it mean that the next array element will be printed as output..am i correct?

NogDog
12-21-2005, 11:40 PM
It means that when you want to have the value of a variable expressed within a double-quoted string, by wrapping the variable name inside of curly braces you help the parser recognize the precise variable name. This is not necessary for simple variable names which are easily determined by the parser, such as "This is a $variable inside a string". But you might need clarification for this: "This_is a {$variable}_inside_a_string". And any time you want to use an array element variable inside a double-quoted string, you need to use the braces as well or the parser may get confused: "This is an {$array['variable']} inside a string".