R00t_R3z R00t_R3z - 1 year ago 66
PHP Question

Assigning an array through foreach PHP

I have the following code:

$data = array();
foreach ($_POST as $field => $value) {
// ex: $field = "1f_fieldname";
if($field[1] == "f")
// $field[0] is numeric
$i = $field[0];
$data = array($i => $value);

the array $data will only print the last element assigned only.



prints the following:

[3] => "value3"

instead of:

[0] => "value1",

[1] => "value2",
[2] => "value2",
[3] => "value3"

What's wrong with it ??

When I print the array from inside the foreach, it prints the whole elements.
But when I print it outside the foreach, it will print only the last one.

Answer Source

This line is wrong:

$data = array($i => $value);

It replaces the entire array with a new array containing just a single element. It should be:

$data[$i] = $value;

to add a new element to the array. But if you have two keys in $_POST with the same number as the first character (e.g. 1f_fieldA and 1f_fieldB), the later one will replace the first one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download