phpevaluationvariable-variables

Change PHP evaluation of $$k[0] from ${$k[0]} to ${$k}[0]


I have a piece of code here that does not work despite me using a $$ on it to treat the string as a variable:

<? foreach (KOHANA::config('list.amenities_forms') as $k => $v) : ?>
    <div class="form">
        <fieldset>
            <legend><?php echo $v ?></legend>
            <input type="checkbox" name="<?=$k?>flag" id="<?=$k?>flag"/>
            <label class="inline"><?=$v?></label>
            
            <label>Description</label>
            <textarea cols="50" rows="5" name="<?=$k?>[]"><?= empty($$k[0]) ? '' : $$k[0]?></textarea>

            <label>Size</label>
            <input type="text" name="<?=$k?>[]" value="<?= empty($$k[1]) ? '' : $$k[1]?>"/>

            <label>Capacity</label>
            <input type="text" name="<?=$k?>[]" value="<?= empty($$k[2]) ? '' : $$k[2]?>"/>
        </fieldset>
    </div>
<? endforeach?>

the function Kohana::config returns this array:

'amenities_forms' => array(
    'meeting_space' => 'Meeting Space',
    'breakfast_room' => 'Breakfast Room',
    'living_quarters' => 'Living Quarters',
    'restaurant' => 'Restaurant',
    'bar' => 'Bar'
)

What could I be doing wrong?


Solution

  • I think the problem is the fact that PHP interprets $$k[0] as using the string from the variable $k[0] as the name of the variable, when you wanted to only use the contents of the $k variable as name of the variable. Using ${$k}[0] instead, should make PHP understand what you wanted do and not use the array index as part of the $k variable.

    For example,

    <?php
    $foo[0] = 'bar';
    $k = 'foo';
    echo ${$k}[0];
    ?>
    

    This will output "bar", but it would not work without the curly braces.