How to get a loop value into one variable

Hi Forum,

I want to get the value of this loop into one variable in php…



for($k=0;$k<$total_records;$k++)
{
    for($j=0;$j<5;$j++)
    {
         $data1[$k][$j];
    }
}

I want to put the output into a variable so that I can echo or print it later on…or whenever required.

Thanks for your consideration.

you need to append the looped variables using .=


$variable = '';
for($k=0;$k<$total_records;$k++)
{
    for($j=0;$j<5;$j++)
    {
        $variable .= $data1[$k][$j];
    }
} 

echo $variable;

Depending on what kind of data you’re storing you could either do what the previous poster suggested. However, if there is a lot of data, you may not want it all stored in one gigantic string. You could actually turn your code above into a function and just call that function when you want to print it. That way you can format it nicely, maybe in a table…



function printRecords($total_records, $data){

echo "<table>\
";

  for($k=0; $k<$total_records; $k++)
  {
      echo "<tr>\
";
      for($j=0; $j<5; $j++)
      {
           echo "<td>" . $data1[$k][$j] . "</td>\
";
      }
     echo "</tr>\
";
  }

echo "</table>";

}