0

创建数组后,我正在尝试设置数组键的值。我知道这会,这确实给出了错误:

Notice: Undefined variable: peter in C:\web\apache\htdocs\test\array.php on line 144 Peter is years old.

$age=array("Peter"=>$ageVal);// Has to come first, since it's inside an include file.

$ageVal = 35; //Comes later.

echo "Peter is " . $age['Peter'] . " years old.";

但是有没有办法在不改变顺序的情况下做到这一点?a)首先创建数组 b)稍后设置数组键的值。

4

3 回答 3

2

是的,您可以通过引用分配数组值来做到这一点,尽管我不建议这样做。

这有效(但我不推荐它):

$age=array("Peter" => &$ageVal);// Has to come first, since it's inside an include file.

$ageVal = 35; //Comes later.

echo "Peter is " . $age['Peter'] . " years old.";

演示

这是我推荐的方式:

$age = array(); // Comes first, since it's inside an include file.

$ageVal = 35; // Comes later.
$age['Peter'] = $ageVal; // Assigns a value to the 'Peter' key in $age

echo "Peter is " . $age['Peter'] . " years old.";
于 2013-06-18T04:45:49.683 回答
1

您可以在一行中设置两个变量。

$age['Peter'] = $ageVal = 35;
于 2013-06-18T04:44:15.910 回答
0

不要在顶部初始化数组。

$age=array();// Has to come first, since it's inside an include file.

$ageVal = 35; //Comes later.
$age['Peter'] = $ageval;  // Set the array element here.

echo "Peter is " . $age['Peter'] . " years old.";
于 2013-06-18T04:44:50.413 回答