"1", "second"...">

How can I split this array into three and put it in a <td> using php?

I have a php array of ten numbers

$arr = array("first" => "1", "second" =>"2", "Third" =>"3", "Fourth" =>"4",
"fifth" =>"5",, "sixth" =>"6", "seventh" =>"7", "eighth" =>"8", 
"ninth" =>"9","tenth"="10");

      

I need to place these values ​​in <td>

by dividing the array by three so my td contains the first td contains the <td>

first three aray values ​​the </td>


second td contains the <td>

next three aray values ​​the </td>


third td contains the <td>

next three aray values </td>


if the remaining values ​​are less than three times should be in another td let's say I now have the tenth value, so my last td should contain the tenth value

+2


a source to share


5 answers


This will do the trick.

    <?php


$array = array("first" => "1", "second" =>"2", "Third" =>"3", "Fourth" =>"4",
"fifth" =>"5", "sixth" =>"6", "seventh" =>"7", "eighth" =>"8", 
"ninth" =>"9","tenth"=>"10");



array_to_td($array, 3);

//$number is the number of elements in a <td></td>.

function array_to_td($array, $number){

 $count = 0;

 foreach($array as $key => $value){
  if ($count == 0){
   print "<td>";  
  }

  $count++;

  print $value;

  if($count == $number ){
   print "</td>";
   $count = 0;
  }


  }
  if ($count != 0){
   print "</td>"; 
  }  

 }

      



You can perform any other operations on this array, as long as it remains unchanged.

+1


a source


You can use array_chunk .



foreach(array_chunk($arr,3) as $row)
{
    echo "<td>"; 
    echo implode(" ",$row);
    echo "</td>"; 
}

      

+7


a source


The PHP function array_splice

was pretty much made to get the job done:

$arr = range(1,10);
while (count($arr)) {
  $three = array_splice($arr,0,3);
  echo "<td>";
  echo implode(" ",$three);
  echo "</td>";
}

      

Output:

<td>1 2 3</td><td>4 5 6</td><td>7 8 9</td><td>10</td>

      


array_splice($arr,0,3)

removes the first 3 elements from $arr

and returns them to$three

+2


a source


Don't know if there is a function that will split such an array. Perhaps do it in for?

$cnt = count($arr);
for($point = 0; $point < $cnt; $point += 3)
{
    echo("<td>".$arr[$point]." ".$arr[$point+1]." ".$arr[$point + 2]."</td>");
}

      

EDIT: Of course, internally you have to check if the values ​​remain. This assumes the length of the array is a multiple of 3 (which you said might not be the case)

+1


a source


See another example

<?php
$arr = array("first" => "1","second" => "2","Third" => "3","Fourth" => "4","fifth" => "5","sixth" => "6","seventh" => "7","eighth" => "8","ninth" => "9","tenth" => "10");
echo "<br>";
print_r($arr);
echo "<br>";

?>

<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td>
<?php
$i=1;
foreach ($arr as $value) {
    echo $value." ";
    if($i%3==0) echo "</td><td>";
    $i++;
}
?>
</td>
</tr>
</table>

      

+1


a source







All Articles