How to create array dynamically?

Posted on

Question :

I would like to dynamically create a array , I tried this way:

$zt = array();
    $zt = ($p_p[0] => $_p_p[1]);

$p_p is an array , where index 0 is the name, and index 1 is the value, 2 name, 3 value ..

$p_p is configured like this, but unfortunately it gives error in line $zt :


Parse error: syntax error, unexpected ‘= >’

If I do this:

$zt = ($p_p[0]);

It does not give error, but the index is “0”, I needed it to be in fact the name, since I’m going to pass this array $zt to POST as if they were fields of one form.


Answer :

So I understand you want $p_p[0] to be the key and $p_p[1] o value, then:

$zt = array();
$zt[$p_p[0]] = $p_p[1];


If you want to create a simple (non-associative) array:

$zt = array();
$zt[] = $p_p[0] => $_p_p[1];

If you want to create an associative array

$zt = array();
$zt[$p_p[0]] = $p_p[0] => $_p_p[1];

The difference is that one automatically assigns the index (numeric) and the second variant can have an index assigned (string).


Leave a Reply

Your email address will not be published. Required fields are marked *