jmenezes
jmenezes

Reputation: 1926

Set an arrays keys value after creating an array

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

Answers (3)

Paul
Paul

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

Demo

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

user1864610
user1864610

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

Joey
Joey

Reputation: 1679

You can set two variables in one line.

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

Upvotes: 1

Related Questions