Get Php Array Values And Print In A Loop
I have a table with 9 rows. The first column should print the name of each participant of the ranking. First of, I did an array containing the names of them: $names = array('Mike',
Solution 1:
$names = array("Mike", "Kyle", "Johnny", "Will", "Vasques");
for($td=0; $td<=9; $td++) {
echo"<tr>";
if ($td == 0) {
foreach ($namesas$name) {
echo"<td>$name</td>";
}
}
echo"<td></td>";
echo"</tr>";
}
Solution 2:
Print the name first then print 9 more td
. (Had to change $x to go from 0
to count($names)-1
to match with indices of $names
)
for($x=0; $x<count($names); $x++) {
echo"<tr>";
echo"<td>$names[$x]</td>";
for($td=2; $td<=10; $td++) {
echo"<td></td>";
}
echo"</tr>";
}
Solution 3:
Use a foreach
loop and an array_fill
for the empty cells
// Set the names array.$names = array("Mike", "Kyle", "Johnny", "Will", "Vasques");
// Set the table cell start key.$table_cell_start_key = 0;
// Set the table cell count.$table_cell_count = 9;
// Set the table cells.$table_cells = implode("", array_fill($table_cell_start_key, $table_cell_count, '<td></td>'));
// Loop through the names array & echo output.foreach($namesas$name) {
echo"<tr>"
. "<td>$name</td>"
. $table_cells
. "</tr>"
;
}
The nice thing about using an array_fill
is you can simple set the values for $table_cells
ahead of the foreach
loop. And then the foreach
loop is just to render content based on the $names
and the extra table cells are just dropped in.
Post a Comment for "Get Php Array Values And Print In A Loop"