Problem iterating an array in php

Asked

Viewed 34 times

0

I have the following code.

$array = array(1,2,3);
$arr1 = array(3, 4, 5);


$data = [];

for($i = 0; $i < count($array); $i++){

    $data["ca"] = $array[$i];

    for($k = 0; $k < count($arr1); $k++){

        $data["ser"] = $arr1[$k];
    }

}

print_r($data);

the idea is that it goes through the whole array, thing it is not doing and as it goes through it prints as follows:

Array ( [ca] => 1 [ser] => 3 )
Array ( [ca] => 2 [ser] => 4 )
Array ( [ca] => 3 [ser] => 5 )
  • 1

    Ever tried to put ['ca'][] = $array[$i]; Because in that case he’s just replacing the value

  • @adventistaam yes, only then it duplicates the values of my array.

  • It is because the second for is within the first. So every time he will repeat

  • @adventistaam yes, but I put in a loop inside another loop just to be able to cross the values, because if I put one outside the other it gives me this result Array ( [ca] => 1, [ca] => 2, [to be] => 1, [to be] => 2 ).

  • 1

    But the values will be the ones in the array. Unless you take the second one for

  • @adventist opa is true only had taken out the second for and put everything into one for, vlw.

  • 1

    I hope it worked

  • Possible duplicate of Mount two-dimensional PHP array

Show 3 more comments

1 answer

0


The problem was solved by taking out the second for and iterate in just one loop

$array = array(1, 2, 3);
$arr1 = array(3, 4, 5);


$data = [];

for($i = 0; $i < count($array); $i++){

    $data["ser"] = $arr1[$i];
    $data["ca"] = $array[$i];
    print_r($data);
}
  • 1

    This way you will only print the last insertion in the $data array... Print_r must be placed inside the for.

  • @recoils-gerbi-neto vlw by touch

  • 1

    Here is another way to do this: https://answall.com/questions/344460/montar-array-bidimensional-php

Browser other questions tagged

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