How to Edit a Grid With PHP
- 1
Open a text editor and create an array in PHP using the array() function. Name the array $table. Place the code inside of <?php and ?> script delimiters.
<?php
$table = array();
?>
- 2
Since $table is an array that contains no values, add three more arrays to the $table array so that $table is an array holding three more arrays. The $table array represents the grid's rows, and the three new arrays represent the grid's columns.
<?php
$table = array(array(), array(), array());
?>
- 3
Add three numeric values to each of the three arrays inside of the $table array. These arrays are now arrays that hold individual values. The values represent data held in the grid's cells.
<?php
$table = array(
array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));
?>
- 4
Use two for loops to display the rows, columns and cells in the $table array. Write a new line after each row to visually distinguish rows from columns in the grid.
<?php
$table = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));
for ($row = 0; $row < 3; $row++)
{
echo "";
for ($col = 0; $col < 3; $col++)
{
echo $table[$row][$col];
}
}
?>
- 5
Edit the cells in the grid, accessing each cell by retrieving each row and column. Add 1 to each cell value.
<?php
$table = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));
for ($row = 0; $row < 3; $row++)
{
echo "";
for ($col = 0; $col < 3; $col++)
{
echo $table[$row][$col];
}
}
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
$table[$row][$col] = $table[$row][$col] + 1;
}
}
?>
- 6
Loop through $table again to display the edited array.
<?php
$table = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));
for ($row = 0; $row < 3; $row++)
{
echo "";
for ($col = 0; $col < 3; $col++)
{
echo $table[$row][$col];
}
}
for ($row = 0; $row < 3; $row++)
{
for ($col = 0; $col < 3; $col++)
{
$table[$row][$col] = $table[$row][$col] + 1;
}
}
for ($row = 0; $row < 3; $row++)
{
echo "";
for ($col = 0; $col < 3; $col++)
{
echo $table[$row][$col];
}
}
?>
- 7
Save the file on the server with the name grid.php and access it in a Web browser. The page shows the original grid and the edited grid.
No comments:
Post a Comment