tags:

views:

54

answers:

2

Is there a way to only print or output 10 elements per row inside a table in PHP from an indexed array with X number of elements of type int.

Maybe some function, I have not heard of?

Or some technique that's used by professionals or beginners alike.

I will embed some code for the TR and TD; however, I was just wondering if there is something I could use to only have 10 elements per row inside of my table.

[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to find solutions or information, thank you.]

+5  A: 

You can use a counter in your loop to keep track of how many <td> elements you have generated in the current row:

echo "<tr>";
$i = 0;
foreach (...)
{
    if ($i++ % 10 == 0)
    {
        echo "</tr><tr>";
    }
    echo "<td></td>";
}
echo "</tr>";
James McNellis
Your code puts only 9 elements in the first row. To fix, initialize $i as 0 instead. I prefer my code as it avoids such an off-by-one error http://en.wikipedia.org/wiki/Off-by-one_error
artlung
+2  A: 

I like using: foreach, array_chunk, and implode to do this. It's better than having to futz with incrementing variables. I suggest you review array basics -- it's powerful stuff.

// here's an array with integers 1 to 50, for example:
$your_array = range(1,50);

// set how many you want in each row
$per_row = 10;

print "<table cellspacing='0' cellpadding='2' border='1'>\n";

Here's the code you can drop in to replace what you have:

foreach (array_chunk($your_array, $per_row) as $set_of_numbers) {
    print "<tr><td>";
    print implode('</td><td>',$set_of_numbers);
    print "</td></tr>\n";
}

And finish with:

print "</table>\n";

That should get you the output you describe, a set of integers in a table, with 10 items per row. Now, if the size of $your_array has a remainder when divided by 10, you may need to pad those cells for looks, but that's secondary.

Output:

<table cellspacing='0' cellpadding='2' border='1'>
<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr>
<tr><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td><td>20</td></tr>
<tr><td>21</td><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td><td>27</td><td>28</td><td>29</td><td>30</td></tr>
<tr><td>31</td><td>32</td><td>33</td><td>34</td><td>35</td><td>36</td><td>37</td><td>38</td><td>39</td><td>40</td></tr>
<tr><td>41</td><td>42</td><td>43</td><td>44</td><td>45</td><td>46</td><td>47</td><td>48</td><td>49</td><td>50</td></tr>
</table>
artlung
Okay, I will start of by review[ing] array basics, followed by foreach, array_chunk, and implode, thank you.
Newb