Jump to content

assigning array key name by variable


spaghettio05

Recommended Posts

To answer your question: variable variables

<?php
$key = "apple";
$arr = array($$key => "fruit");
?>

 

Although, I prefer keys and values like:

<?php
$arr = array('fruit' => 'apple');


echo 'Hmmm, what kind of fruit do we have?  Oh an, ' . $arr['fruit'] . '!';
?>

To answer your question: variable variables

<?php
$key = "apple";
$arr = array($$key => "fruit");
?>

This will throw an undefined variable error.

The OP's original code was correct, I suspect the issue is in the retrieval.

$key = "apple";
$arr = array($key => "fruit");
print_r($arr);
// Output: Array ( [apple] => fruit ) 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.