I would like to create table for the below for loop. It prints the square of numbers from 1 to 10. I want to declare a html table and want to show the output like this
"1 square is" one cell, "1" in second cell
"2 square is" in one cell, "4" in second cell
<?php
for ($i=1;$i<=10;$i++)
echo $i . ' square is ' . $i*$i . "<br>";
?>
Thanks alot.
<?php
echo '<table>';
for ($i=1;$i<=10;$i++)
echo '<tr><td>' . $i . ' square is </td><td>' . $i*$i . "</td></tr>";
echo '</table>';
?>
Related
Hello all! This is my first question in stackoverflow so I hope I follow the rules good enough. :)
For my PHP class I have an exercise that makes it difficult for me: Text with about 4 variables in it, all are stored in arrays (one array for each variable, 3 values for each variable).
Position [0] of each array goes in the first echo text, position [1] of each array goes in the second text and so on.
How to echo the text 3 times using all values stored in the array? In the code I must use the main text only 1 time.
$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');
echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " . $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " . $course_name[1] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " . $course_name[2] . " will last for two days.";
This is what I did by myself, but as you see in the code I have 3 times the main text.
Thank you in advance.
Normally you go trough arrays with some type of a loop.
To name a few types of loops:
for
while
foreach
In this case the perfect fit is a foreach loop.
It simply goes through each element of the array, but because you have a associative array and two indexed array you also need a counter.
$counter = 0;
foreach($u_name as $key=>$value){
echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " . $course_name[$counter] . " will last for two days.";
echo "<br>";
$counter++;
}
If still are any questions left, don't mind to ask.
I am working on a "boxing records" database for a school project. The loop retrieves records from a SQL statement. I want to add a "VS" string of text between every other two lines in order to show records outputted somewhat like this.
Upcoming Fights
Sergey Kovalev (28-0-25)
VS
Jean Pascal (30-3-17)
Another Boxer (123-0-5)
VS
Some Boxer (123-3-1)
However, my current loop outputs like this
Sergey Kovalev (28-0-25)
VS
Jean Pascal (30-3-17)
VS
Another Boxer (123-3-1)
VS
Some Other Boxer (123-3-1)
VS
The loop I currently have is the following
foreach($records as $record) {
$i = 0;
echo $record['name'] . " (" . $record['wins'] . "-" . $record['losses'] . "-" . $record['kos'] . ")" . "<br>";
$i=$i*2;
if($i%2 == 0)
{
echo "VS <br/>";
}
else{
echo "<br />";
}
I know I could probably change the SQL in order to display two fighters in the same row, and then append "vs" on the echo, but I thought that just modifying the for loop would work by using a variable counter $i. I thought it would be pretty easy to make the "VS" appear between every two rows but im missing something in my logic.
You need to increment value of $i by one rather than multiplying it by 2 and initialize $i outside foreach loop.
$i = 0; // Initialize counter here
foreach($records as $record) {
echo $record['name'] . " (" . $record['wins'] . "-" . $record['losses'] . "-" . $record['kos'] . ")" . "<br>";
if($i%2 == 0)
{
echo "VS <br/>";
}
else
{
echo "<br />";
}
$i++; // Increment counter here
}
I am getting data from a my database. There is a admin panel also where people can add data to the database. The data gets on the page but some of the rows(<tr>) have less table data tags(<td>) than others. thus the table is not justified. Is there a way to add empty <td> to rows that need them? I have tried everything but i can't figure it out.
Picture on how the table looks at the moment:
The green numbers are the total sum of points but it's not clear because the table rows are jagged. How to fix tis?
If there is a jQuery solution that's also fine.
my code:
echo "<table class=\"zebra1\">";
echo "<th>N. </th>" . "<th>Team name: </th>" . "<th colspan=\"5\">Points: </th>" . "<th>Sum: </th>";
$numbering =1;
$query2 = $db->prepare("SELECT pisteet_1 As PIY, pisteet_2 as PIK, nimi As NIM, opisto As OPI, pisteet.kaupunki_id As KA FROM
pisteet INNER JOIN joukkueet ON joukkueet.id = pisteet.team_id INNER JOIN oppilaitokset ON oppilaitokset.opisto_id = joukkueet.opisto_id ORDER BY team_id ASC");
$query2->execute();
$results = $query2->fetchAll();
$tableD = array();
foreach ($results as $key) {
$tableD[$key['NIM']][] = array('PIY'=>$key['PIY'],'PIK'=>$key['PIK'],'KA'=>$key['KA'], 'OPI'=>$key['OPI']);
}
foreach($tableD as $teamN=>$values2){
//Echoing the Team name
echo "<tr class=\"all " . $values2[0]['KA'] . "\">";
echo "<td>" . $numbering . "</td>";
echo "<td>" . $teamN ."<span>" . $values2[0]['OPI'] ."</span></td>";
$sum1=0;
$sum2=0;
//Echoing the points
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
}
//Echoing the total sum of points
echo '<td class="Sum">'.$sum1.'/'.$sum2."</td>";
echo "</tr>";
$numbering ++;
}
echo '</table>';
I have a variable named: $colspancalculated that has the longest row: at the moment it stores the value 5.
Assuming you have a fixed number of columns (I assume this because you've got a colspan on your table header cell), you need to output the td elements as you are doing, or output blank cells if the records don't exist.
Consider something like this instead of your foreach:
// Echoing the points - as you mention in your comment, you've calculated
// the maximum column size as $colspancalculated - so you that as your upper limit
for($i = 0; $i < $colspancalculated; $i++) {
if(!isset($values2[$i]['PIY'])) {
// This record doesn't exist! Output a blank cell
echo '<td></td>';
continue;
}
// Otherwise, output the cell and do your calculations
echo '<td class="points">' . $values2[$i]['PIY'] . '/' . $values2[$i]['PIK'] . '</td>';
$sum1 += $values2[$i]['PIY'];
$sum2 += $values2[$i]['PIK'];
}
Instead of a foreach loop, use a for loop -- or, since you have to work with an iterator, anyway, just do:
$i = $numberOfColumnsLeftAtThisPointInYourScript
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
$i--;
}
while($i > 0){
echo '<td> </td>';
$i--;
}
I am learning PHP and have been agonizing over how to write my code properly. I have a textarea that accepts user input which is several lines of coordinates (PT# Northing Easting) separated by spaces.
I have the form pass the textarea input to a php script to handle it.
I can get a foreach loop to do exactly what I want but only local to the foreach loop, the variables do not get passed to the outside of the loop.
I know this is a global variable scope issue, for the life of me I can't resolve this...
Below is my PHP code, I left out the HTML form I have no issues with it and know the textarea is being passed properly.
**Sample data that I am inputing:
1 728258.24000 774337.29700
2 728232.15735 774277.54650
3 728326.39614 774216.82428**
<?php
$i = 0;
$j = 0;
//The code below explodes my textarea into a string array
//of separated lines.
$textArea = explode("\r", $_POST['textArea']);
$textNum = array();
//The code below works internally, but the values remain here
//I wanted to get them to the variables below so I can do work
//to them.
foreach ($textArea as $textRows) {
//The code below explode the lines into elements separated by a space
$textRow = explode(" ", $textRows);
foreach ($textRow as $textItem) {
$textNum[i][j] = $textItem;
//The code below works within a local context
echo "(" . $i . " " . $j . ")" . $textNum[i][j] . "</br>";
$j++;
}
$i++;
$j = 0;
}
//The code below is not receiving values from the foreach loop
//I know this has something to do with the variable scope
//I must be way off in my approach any help would be appreciated!
echo "</br>";
echo "</br> 0 0 " . $textNum[0][0];
echo "</br> 0 1 " . $textNum[0][1];
echo "</br> 0 2 " . $textNum[0][2];
echo "</br> 1 0 " . $textNum[1][0];
echo "</br> 1 1 " . $textNum[1][1];
echo "</br> 1 2 " . $textNum[1][2];
echo "</br> 2 0 " . $textNum[2][0];
echo "</br> 2 1 " . $textNum[2][1];
echo "</br> 2 2 " . $textNum[2][2];
echo "</br> 3 0 " . $textNum[3][0];
echo "</br> 3 1 " . $textNum[3][1];
echo "</br> 3 2 " . $textNum[3][2];
?>
I hope I have explained this well enough, and appreciate any help I can get! Thanks!
There is an error in your second loop:
$textNum[i][j] = $textItem;
have to be:
$textNum[$i][$j] = $textItem;
You, need to prepend $ before your variables, i.e $textNum[$i][$j] instead of $textNum[i][j], also, it's best to initialize $i and $j and set them to 0 before the foreach loop.
I'm using the code below to build a table, but because the values in my database table are constantly incrementing, I'm doing some math to work out differences in values (numerically) but this has screwed up the table layout somehow. I've included a screenshot so you can see that the first row beneath the table header is just not right.
$column is a $_GET value from the user.
$sql = "select * from (select * from mash order by tstamp desc limit 10) s order by s.id";
$result = mysql_query($sql);
$previous = 0;
$firstRun = true;
echo "<table id='dataTable' border='1'>";
echo "<tr><th>Date</th>
<th>Value</th></tr>";
while($row = mysql_fetch_array($result)){
$difference = $row[$column] - $previous;
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
echo "<td>" . $difference . "</td></tr>";
$previous = $row[$column];
$firstRun = false;
}
echo "</table>";
My question: Can anyone spot from the code, why the first row would come out like this?
The problem comes from this line:
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
If you don't want to display the first line, use the brackets:
if (!$firstRun){
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
echo "<td>" . $difference . "</td></tr>";
}
It's your "if" statement. It doesn't echo anything on the first run, so the starting tr and td don't get echoed, so you end up with an incorrect row (ended with the /tr tag) containing only a single td value. Did you mean to put brackets around the two echo statements so that they only happen when firstrun is false?
first of all, where is $column defined ?
$difference = $row[$column] - $previous;
second, this is only executed as of the second iteration
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
This means that the first time in the while loop, you are not creating the table row <tr> , although I'm guessing the browser is able to "fix" the missing tag, but this would be the reason why -32722 appears in the first column.