How to create array dynamically?

Asked

Viewed 1,263 times

3

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

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

$p_p is a 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 gives error in line $zt:

Parse error: syntax error, Unexpected '=>'

If I do so:

$zt = ($p_p[0]);

no mistake, but the index is "0", I needed it was in fact the name, since I will pass this array $zt for POST as if they were fields of a form.

  • 1

    Look, I found the solution, but I didn’t find it logical. I declared as array $zt, like this: $zt = array();, then I hoped that what $zt gets behaves like array, but I needed to change for that: array($p_p[0] => $_p_p[1]);, that is, I informed that it was array(again) what I put inside.

  • 1

    You had to declare again that the $zt is an array because you are overwriting the variable $zt.

  • perfect! thanks

2 answers

7

From what I understand you want $p_p[0] be the key and $p_p[1] the value, then:

$zt = array();
$zt[$p_p[0]] = $p_p[1];
print_r($zt);
  • Luiz, thank you for the answer, I did not know that an index could receive a value like this!

2

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

$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 assigns the index automatically (numerical) and the second variant can have an index assigned (string).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.