Dexy_Wolf
Dexy_Wolf

Reputation: 999

How to dynamicly set a array variable?

I have a problem with this code:

$a['i'] = 1;

$b = '$a[\'i\']';
echo $$b;

It display an error:

Notice: Undefined variable: $a['i'] in test.php on line 6

Is it possible to create dynamic array variable?

Thanks for your time.

EDIT: In my example I am trying to edit an multidimensional array. There is a problem when I try to add data to my array (JSON). I don't have fixed dimension of array, it my be 2 or more dimension (I am building a model for Web form, and I want to add invalid value to JSON).

Now in one of the methods of Web form object I have code which checks repopulation object to add invalid value if needed.

I can not just add a value to JSON array, I need to edit it on multidimensional level.

For now I came up on solution to dynamically generate variable name and, then, edit it. If someone have solution it will be appreciated.

private $form = array(
        'form_contact'=>array(
            'attr'=>array('tag'=>'FORM', 'method'=>'post'),

        'elem'=>array(

            'fs_contact'=>array(
                'attr'=>array('legend'=>'Kontakt', 'tag'=>'FSET'),
            'elem'=>array(

                'name'=>array(
                    'attr'=>array('SPAN'=>'Ime i prezime', 'title'=>'Unesite Vaše ime i prezime', 'tag'=>'INPUT', 'type'=>'text'),
                    'validat'=>array('req'=>'noscript', 'length'=>255),
                    'invalid'=>true), // Holds info that this is invalid
                'www'=>array(
                    'attr'=>array('SPAN'=>'Web sajt', 'title'=>'Unesite Vaš sajt', 'tag'=>'INPUT', 'type'=>'text'),
                    'validat'=>array('length'=>255)),
                'email'=>array(
                    'attr'=>array('SPAN'=>'E-mail', 'title'=>'Unesite Vaš email', 'tag'=>'INPUT', 'type'=>'text'),
                    'validat'=>array('req'=>'email', 'length'=>255)),
                'message'=>array(
                    'attr'=>array('SPAN'=>'Poruka', 'cols'=>'60', 'rows'=>'5', 'title'=>'Unesite Vašu poruku', 'tag'=>'TEXTA', 'value'=>'nesto'),
                    'validat'=>array('req'=>'all')),
                'submit_new_contact_form'=>array(
                    'attr'=>array('tag'=>'INPUT', 'type'=>'submit', 'value'=>'Pošalji poruku!'))
                ))// FS end
            )) // Form end      
        );// Array end

Upvotes: 0

Views: 107

Answers (1)

BoltClock
BoltClock

Reputation: 724452

You can't do it that way, as PHP thinks you're looking for a variable with the name $a['i'], rather than the 'i' key in the $a array.

The proper, and conventional, way is to use a dynamic key/index instead:

$b = 'i';
echo $a[$b];

Upvotes: 1

Related Questions