Reputation: 1926
I'm trying to set an array key's value after I've created the array. I know this will, and this does give the error :
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.";
But is there some way to do this just like this without changing the sequence? a) Array gets created first b) Array key's value is set later.
Upvotes: 0
Views: 120
Reputation: 141917
Yes, you can do this by assigning the array value by reference, although I would not recommend doing this.
This works (but I don't reccomend it):
$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.";
This is the way I recommend doing it instead:
$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.";
Upvotes: 2
Reputation:
Don't initialise your array at the top.
$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.";
Upvotes: 0