创建数组后设置数组键值

时间:2013-06-18 04:40:54

标签: php

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

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)稍后设置数组键的值。

3 个答案:

答案 0 :(得分:2)

是的,你可以通过分配数组值by reference来做到这一点,虽然我不建议这样做。

这有效(但我不推荐):

$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.";

Demo

这是我推荐的方式:

$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.";

答案 1 :(得分:1)

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

$age['Peter'] = $ageVal = 35;

答案 2 :(得分: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.";