Brandi Evans
Brandi Evans

Reputation: 81

How do I push to a multidimensional array in php?

I need a simple multidimensional array but don't know how to push it. I need to store a string, then an integer.

string(zip code) then my integer.

93801, 123

$zips = array();
$i = 1;

if(isset($_POST['zip' + $i])) {
    array_push($zips, $_POST['zip' = $i] $_POST['fed' + $i]);
    $i++;
}

I get a syntax error on the push line, but if I add a comma it just makes the two items separate.

Upvotes: 2

Views: 107

Answers (3)

Kent Munthe Caspersen
Kent Munthe Caspersen

Reputation: 6888

use int array_push ( array &$array , mixed $var [, mixed $... ] ) that takes a variable number of parameters like this

array_push($zips, $_POST['zip' . $i], $_POST['fed' . $i]);

Upvotes: 3

insertusernamehere
insertusernamehere

Reputation: 23580

You can push it to the end as a new array:

$zips[] = array($_POST['zip' + $i], $_POST['fed' + $i]);

And I guess you mean $_POST['zip' + $i] instead of $_POST['zip' = $i] and you may also check $_POST['fed' + $i] for existence. And also remember that + is not a concatenation of strings in PHP. This will always result in $i. You can check this using var_dump('fed' + $i);. If you want to get $_POST['fed1'] use $_POST['fed' . $i] instead.

Upvotes: 2

Matt Cain
Matt Cain

Reputation: 5768

Put the values into an array with array() and push that into the $zips array.

array_push($zips, array($_POST['zip' + $i], $_POST['fed' + $i]));

As insertusernamehere mentions, you probably want $_POST['zip' . $i] for concatenation :)

Upvotes: 2

Related Questions