0

I need to display array of 10 numbers in three columns. if i add another number some like, 11 it must add below 10. as numbers increasing row can be increased not the column, can any one say?

1 4 7 10
2 5 8
3 6 9

am getting 10 in fourth column, but i need it in third column. and row will get increased like

1 4 8
2 5 9
3 6 10
4 7
5
  • can you give an example output of what you really want? Commented Jun 29, 2011 at 7:42
  • 1
    Three columns means 10 ends up on a row of its own. Why must 11 be displayed under it? Can you show an example? Commented Jun 29, 2011 at 7:42
  • I swear the same questions was asked very recently, but I can't find it right now... Commented Jun 29, 2011 at 7:55
  • 1
    Here you go: How do I distribute values of an array in three columns? Browser history search function FTW. Commented Jun 29, 2011 at 7:59
  • was asked by two persons in the same location, any chance it's homework from the same class? :D (I know India is big) Commented Jun 29, 2011 at 8:13

2 Answers 2

1

Display Output in table..

<?php
$arr = array("1","2","3","4","5","6","7","8","9","10", "11", "12", "13");

$row= ceil(count($arr)/3);
echo "<table border='1'>";
for($i = 1; $i <= $row; $i++) {
    echo "<tr>";
    echo "<td>". $i ."</td>";
    $k = 0;
    $pre = 0;
  for($j = 1; $j <= 2; $j++) {
    if($pre == 0)
      $pre = $k = $i + $row;
    else
      $pre = $pre + $row;

    if($pre <= max($arr))
      echo "<td>". $arr[$pre-1] ."</td>";
  }
  echo "</tr>";
}
echo "</table>";
?>

Output will be:

1   6   11
2   7   12
3   8   13
4   9
5   10
Sign up to request clarification or add additional context in comments.

2 Comments

instead of writing the enitre array like this $arr = array("1","2","3","4","5","6","7","8","9","10", "11", "12", "13");, u can use $arr = range(1,13);
good suggestion. but here my goal was to display data in desired format.
0

Try this...

<?php
$arr = array("1","2","3","4","5","6","7","8","9","10", "11", "12", "13", "14");

$row= ceil(count($arr)/3);

for($i = 1; $i <= $row; $i++) {
    echo $i;
    $k = 0;
    $pre = 0;
  for($j = 1; $j <= 2; $j++) {
    if($pre == 0)
      $pre = $k = $i + $row;
    else
      $pre = $pre + $row;

    if($pre <= max($arr))
      echo " ". $arr[$pre-1] ." ";
  }
  echo "<br>";
}

?>

Output when 14 element:

1 6 11
2 7 12
3 8 13
4 9 14
5 10 

Output when 11 element:

1 5 9
2 6 10
3 7 11
4 8 

Output when 13 element:

1 6 11
2 7 12
3 8 13
4 9
5 10 

1 Comment

yes jeni very easy.. I add new answer that add result in table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.