art
art

Reputation: 306

Array being overriden at each iteration of for loop

How can I store changing variables ($i,$j) in the info array ,So that it contains all the values not just the last?

<?php
    for($i=0,$j=0;$i<3;$i++,$j++){
        $members=array($i,$j);
        $info=array();
        foreach ($members as $k) { 
            $info[]=$k;
        }
    }    
    print_r($info);
?>

Upvotes: 0

Views: 55

Answers (2)

art
art

Reputation: 306

This can also be done

<?php
    $info=array();
    for($i=0,$j=0;$i<3;$i++,$j++){
    $info=array_merge($info,array(array($i,$j)));

    }
    print_r($info);
    ?>

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

Just put array variable $info to outside of loop, It is being overwrite in each iteration.

<?php
$info=array();
for($i=0,$j=0;$i<3;$i++,$j++){
$members=array($i,$j);

foreach ($members as $k) { 
    $info[]=$k;
}
}
print_r($info);
?>

check your output : https://eval.in/608707

I don't know you purpose, but you can also do it by many ways

  1. https://eval.in/608744

  2. https://eval.in/608721

Upvotes: 1

Related Questions