How can I print a chess table in PHP without using for loops, is it possible to do it with conditional and logical statements only?
<table width = "270px" cellspacing = "0px" cellpadding = "0px" border = "1px" bordercolor = "gray">
<?php
$value = 0;
for($col = 0; $col < 8; $col++) {
echo "<tr>";
$value = $col;
for($row = 0; $row < 8; $row++) {
if($value%2 == 0) {
echo
"<td height=40px width=20px bgcolor=black></td>";
$value++;
}
else {
echo
"<td height=40px width=20px bgcolor=white></td>";
$value++;
}
}
echo "</tr>";
}
?>
You could use str_repeat:
<table width="270px" cellspacing="0" cellpadding="0" border="1px" bordercolor="gray">
<?php
$td = '<td height="40px" width="20px" bgcolor=';
$black = "$td'black'></td>";
$white = "$td'white'></td>";
echo str_repeat("<tr>" . str_repeat($black . $white, 4) . "</tr><tr>"
. str_repeat($white . $black, 4) . "</tr>", 4);
?>
</table>
One solution is to use build-in loops derived from some functions, here array_walk(only to avoid explicit for).But it the end the algorithm is the same. It's only a trick !
<?php
$arr = array_fill(0,64,1);
array_walk($arr,"construct");
array_walk($arr,"display");
function construct(&$item, $key)
{
$color=$key%2;
$i=($key-$key%8)/8 + 1;
if($i%2==0)
$color = ($color+1)%2;
$color = $color%2==0 ? "white" : "black";
$j=$key%8+1;
$item = new Square($i,$j,$color);
}
function display($item, $key)
{
if($key%8==0) echo "<br>";
echo $item." ";
}
class Square
{
public $i;
public $j;
public $color;
public function __construct($i,$j,$color)
{
$this->i=$i;
$this->j=$j;
$this->color=$color;
}
public function __toString()
{
return "[".$this->i.",".$this->j."]=".($this->color);
}
}
?>
Output:
[1,1]=white [1,2]=black [1,3]=white [1,4]=black [1,5]=white [1,6]=black [1,7]=white [1,8]=black
[2,1]=black [2,2]=white [2,3]=black [2,4]=white [2,5]=black [2,6]=white [2,7]=black [2,8]=white
[3,1]=white [3,2]=black [3,3]=white [3,4]=black [3,5]=white [3,6]=black [3,7]=white [3,8]=black
[4,1]=black [4,2]=white [4,3]=black [4,4]=white [4,5]=black [4,6]=white [4,7]=black [4,8]=white
[5,1]=white [5,2]=black [5,3]=white [5,4]=black [5,5]=white [5,6]=black [5,7]=white [5,8]=black
[6,1]=black [6,2]=white [6,3]=black [6,4]=white [6,5]=black [6,6]=white [6,7]=black [6,8]=white
[7,1]=white [7,2]=black [7,3]=white [7,4]=black [7,5]=white [7,6]=black [7,7]=white [7,8]=black
[8,1]=black [8,2]=white [8,3]=black [8,4]=white [8,5]=black [8,6]=white [8,7]=black [8,8]=white
For html grid, just adapt display.
function displayHtml($item, $key)
{
if($item->i==1 && $item->j==1)
echo '<table width="270px" cellspacing="0" cellpadding="0" border="1px" bordercolor="gray">';
if($item->j%8==1)
echo "<tr>";
echo "<td height=40px width=20px style='background-color:".$item->color."'></td>";
if($item->j%8==0)
echo "</tr>";
if($item->i==8 && $item->j==8)
echo "</table>";
}
Related
I am new to PHP, iam trying to color the cells of column4,column7,column9 based on condition which you can see in the IF block,below is my code what i tried,kindly help me to understand how to achieve this. i am using array because i have got more than 80 columns,in below example iam showing only 10 for explaining.
<?php
$con=mysqli_connect("server","user","password","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table1");
echo "<table id='table_id' class='mytable'>
<thead>
<tr>
<th class='heading'>Column1</th>
<th class='heading'>Column2</th>
<th class='heading'>Column3</th>
<th class='heading'>Column4</th>
<th class='heading'>Column5</th>
<th class='heading'>Column6</th>
<th class='heading'>Column7</th>
<th class='heading'>Column8</th>
<th class='heading'>Column9</th>
<th class='heading'>Column10</th>
</tr>
</thead>";
echo "<tbody>";
while ($row = mysqli_fetch_array($result))
{
$colorfields = array($row['Column4'],$row['Column7'],$row['Column9']);
if ($colorfields < 195 && $colorfields !='')
$classname = "red";
else if($colorfields >= 195 && $colorfields < 199.99)
$classname = "yellow";
else if($colorfields >= 199.99)
$classname = "green";
echo "<tr>";
echo "<td class='normal_cell'>" . $row['Column1']."</td>";
echo "<td class='normal_cell'>" . $row['Column2']."</td>";
echo "<td class='normal_cell'>" . $row['Column3']."</td>";
echo "<td class=".$classname.">". $row['Column4']."</td>";
echo "<td class='normal_cell'>" . $row['Column5']."</td>";
echo "<td class='normal_cell'>" . $row['Column6']."</td>";
echo "<td class=".$classname.">". $row['Column7']."</td>";
echo "<td class='normal_cell'>" . $row['Column8']."</td>";
echo "<td class=".$classname.">". $row['Column9']."</td>";
echo "<td class='normal_cell'>" . $row['Column10']."</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
?>
I'd write a function that returns the 'red', 'yellow' or 'green', depending the value that is passed in as an argument.
function class_from_val($val) {
$classname = '';
if( $val < 195 && $val !='' ) {
$classname = 'red';
} else if( $val >= 195 && $val < 199.99 ) {
$classname = 'yellow';
} else if( $val >= 199.99 ) {
$classname = 'green';
} else {
// ? val = ""
}
return $classname;
}
Then I'd call the function where I need the classname returned
echo "<td class='normal_cell'>" .$row['Column3']."</td>";
echo "<td class='".class_from_val($row['Column4'])."'>".$row['Column4']."</td>";
echo "<td class='normal_cell'>" .$row['Column5']."</td>";
echo "<td class='normal_cell'>" .$row['Column6']."</td>";
echo "<td class='".class_from_val($row['Column7'])."'>".$row['Column7']."</td>";
Follow these general principles:
indent the code and space it
choose carefully your variable names
divide and rule (use functions)
example:
function getClassName($col, $field) {
if ( !in_array($col, [ 'Column4', 'Column7', 'Column9' ]) || empty($field) )
return 'normal_cell';
if ( $field >= 199.99 )
return 'green';
if ( $field >= 195 )
return 'yellow';
return 'red';
}
$cellFormat = '<td class="%s">%s</td>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
foreach ($row as $col => $field) {
printf($cellFormat, getClassName($col, $field), $field);
}
echo '</tr>';
}
I created a code that converts characters to binary and make table cells black/white corresponding to the ones and zeros. This is my code:
$str_splt = str_split($text);
echo "<table>";
for ($a=0;$a < count($str_splt);$a++) {
$bits = array(128,64,32,16,8,4,2,1);
$store = array(0,0,0,0,0,0,0,0);
$inp = ord($str_splt[$a]);
for ($x=0;$x < count($bits);$x++) {
if ($bits[$x] <= $inp) {
$inp = $inp - $bits[$x];
$store[$x] = 1;
} else {
$store[$x] = 0;
}
};
$store_rvs = array_reverse($store);
echo "<tr>";
for ($b=0;$b < count($store_rvs);$b++) {
if ($store_rvs[$b] == '1') {
echo "<td id=\"blk\"></td>";
}
else {
echo "<td></td>";
}
}
echo "</tr>";
}
echo "</table>";
Its output looks like this ($text = "ABCDEFGH"):
As you can see it's 8x8 table. I want to add the next set of bytes to the side of that table like this:
Each 8x8 table is a group. The two images above is group 1 and group 2:
I want to display the tables like this but I can't find the solution.
I did it in this way. Ignore my css if you are fine with yours. I replaced the id tag with class because each id should be defined once only.
echo "<html><head>";
echo "<style type='text/css'>";
echo " table, td { padding:0px; margin:0px; }";
echo " td.cell { width:15px; height:15px; }";
echo " td.blk { background-color:black; }";
echo " td.wht { background-color:yellow; }";
echo "</style>";
echo "</head><body>";
$text = "ABCDEFGH";
$text.= "ABCDEFGH";
echo "<table><tr><td><table>";
for($a=0; $a<strlen($text); $a++) {
$chr = substr($text,$a,1);
$bits = array(128,64,32,16,8,4,2,1);
$store = array(0,0,0,0,0,0,0,0);
$inp = ord($chr);
for($x=0; $x<count($bits); $x++) {
if($bits[$x] <= $inp) {
$inp = $inp - $bits[$x];
$store[$x] = 1;
} else {
$store[$x] = 0;
}
}
$store_rvs = array_reverse($store);
if($a % 8 === 0) {
echo "</table></td><td><table>";
}
echo "<tr>";
for($b=0; $b<count($store_rvs); $b++) {
if($store_rvs[$b] == '1') {
echo "<td class='cell blk'></td>";
} else {
echo "<td class='cell wht'></td>";
}
}
echo "</tr>";
}
echo "</table></td></tr></table>";
Morning,
I have some code that takes a string of shoe sizes, explodes it and then puts it in a table. The code works perfectly and the info is displayed correctly on the page but after the table there is always a few 1's after the table. I'm really confused about this.
So the table looks like this (in columns of three on the webpage)
Available in the following sizes:
3 4 5
6 9 10
111
Here's the Codes, for the purpose of the example $x = 3|4|6|10|9
function get_sizes_pipe($x) {
$counter = 0;
$splits = explode("|",$x);
asort($splits);
$x = print "<table class='greentable'>";
$x .= print "<thead><tr><th scope='col' colspan='3' abbr='Starter'>Available in the following sizes:</th></tr></thead><tbody><tr>";
foreach ($splits as $split) {
$entry = print "<td>".$split."</td>";
if($counter == 2){
$entry .= print "</tr><tr>";
$counter =0;
} else {
$counter++;
}
}
if($counter == 1){
$entry .= print "<td></td><td></td>";
}elseif ($counter == 2) {
$entry .= print "<td></td>";
}
$x.= $entry;
$x.= print "</tr></tbody></table>";
return $x;
}
I'd really appreciate any help.
Thanks
Chris
I don't know why do you concatenate print with some variable, but you should know that function print returns 1 (always) as a result of execution, so doing
$x .= print 'some value';
is the same as
print 'some value';
$x .= 1;
try this:do not use print you are already appending it to $x just echo $x;
<?php
function get_sizes_pipe($x) {
$counter = 0;
$splits = explode("|",$x);
asort($splits);
$x = "<table class='greentable'>";
$x .= "<thead><tr><th scope='col' colspan='3' abbr='Starter'>Available in the following sizes:</th></tr></thead><tbody><tr>";
foreach ($splits as $split) {
$entry .= "<td>".$split."</td>";//use . to concate here
if($counter == 2){
$entry .= "</tr><tr>";
$counter =0;
} else {
$counter++;
}
}
if($counter == 1){
$entry .="<td></td><td></td>";
}elseif ($counter == 2) {
$entry .= "<td></td>";
}
$x.= $entry;
$x.="</tr></tbody></table>";
echo $x;
}
get_sizes_pipe("1|2|3|4");
Rather than using string concatenation ( which becomes inefficient with large strings ) add html strings to an array and return the flattened html from your function.
function get_sizes_pipe($x) {
$counter = 0;
$splits = explode("|",$x);
asort( $splits );
$html=array();
$html[]="
<table class='greentable'>
<thead>
<tr>
<th scope='col' colspan='3' abbr='Starter'>Available in the following sizes:</th>
</tr>
</thead>
<tbody>
<tr>";
foreach( $splits as $split ) {
$html[]="<td>".$split."</td>";
if( $counter == 2 ){
$html[]="</tr><tr>";
$counter=0;
} else {
$counter++;
}
}
$html[]=( $counter == 1 ) ? "<td></td><td></td>" : "<td></td>";
$html[]="
</tr>
</tbody>
</table>";
return implode( PHP_EOL, $html );
}
/* call your function with whatever value of `$x` you need */
echo get_sizes_pipe( $what_is_x );
Currently I have a table order by
A B C D
E F G H
but I would like to order the table by
A E
B F
C G
D H
Code:
for($i=0;$i<=count($aFiles);$i++)
{
if($i%5==0)
{
echo "</tr><tr>";
}
echo '<td><a>'.$aFiles[$i].'</a></td>';
}
echo '</tr>';
echo '</table>';
Files are already sorted a-z in $aFiles.
$aFiles = array('a','b','c','d', 'e', 'f', 'g');
$iColumnNumber = 2;
$iRowMaxNumber = ceil(count($aFiles) / $iColumnNumber);
$iTableRow = 0;
$iTableColumns = 1;
$aTableRows = array();
// make array with table cells
foreach ($aFiles as $sFile)
{
if ($iTableRow == $iRowMaxNumber)
{
$iTableRow = 0;
$iTableColumns++;
}
if (!isset($aTableRows[$iTableRow]))
{
$aTableRows[$iTableRow] = array();
}
$aTableRows[$iTableRow][] = '<td>' . $sFile . '</td>';
$iTableRow++;
}
// if there is odd number of elements
// we should add empty td elements
for ($iTableRow; $iTableRow < $iRowMaxNumber; $iTableRow++)
{
if (count($aTableRows[$iTableRow]) < $iTableColumns)
{
$aTableRows[$iTableRow][] ='<td>empty</td>';
}
}
// display table
echo '<table>';
foreach ($aTableRows as $aTableRow)
{
echo '<tr>';
echo implode('', $aTableRow);
echo '</tr>';
}
echo '</table>';
Simple Approach using HTML trick:
echo '<div class="tbl_group"><table>';
for($i=0;$i<=count($aFiles / 2);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
echo '<div class="tbl_group"><table>';
for($i=$aFiles / 2;$i<=count($aFiles);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
For the CSS:
.tbl_group {
float: left;
}
With this approach, 2 tables are built side-by-side. float: left CSS will auto adjust the position of the tables.
Assuming you know the number of rows you want, you don't need to resort anything, just add some logic in your loop that generates the <td>s :
$size = count($aFiles);
echo '<table><tr>';
for($i=0;$i<=ceil($size/2);$i++) {
if($i%2==0) {
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo "</tr><tr>";
} else {
if(isset($aFiles[$i+floor($size/2)])) {
echo '<td><a>'.$aFiles[$i+floor($size/2)].'</a></td>';
}
}
}
echo '</tr></table>';
Example bellow also works with associative array + arrays with odd elements.
Code for associative AND indexed array :
$aFiles = ['test'=>"A","B",'c'=>"C","D","E","F",'g'=>"G","H",'iii'=>"I"];
$aKeys = array_keys($aFiles);
$aRows = ceil(count($aFiles) / 2);
echo '<table>';
for($i=0; $i < $aRows; $i++) {
echo
'<tr>' .
' <td>' . $aFiles[$aKeys[$i]] . '</td>' .
' <td>' . (isset($aKeys[$i+$aRows]) ? $aFiles[$aKeys[$i+$aRows]] : 'empty') . '</td>' .
'</tr>';
}
echo '</table>';
Code for ONLY indexed array :
$aFiles = ["A","B","C","D","E","F","G","H","I"];
$aRows = ceil(count($aFiles) / 2);
echo "<table>";
for($i=0; $i < $aRows; $i++) {
echo
"<tr>" .
" <td>" . $aFiles[$i] . "</td>" .
" <td>" . (isset($aFiles[$i+$aRows]) ? $aFiles[$i+$aRows] : "empty") . "</td>" .
"</tr>";
}
echo "</table>";
Output for both examples is identical :
<table>
<tr>
<td>A</td>
<td>F</td>
</tr>
<tr>
<td>B</td>
<td>G</td>
</tr>
<tr>
<td>C</td>
<td>H</td>
</tr>
<tr>
<td>D</td>
<td>I</td>
</tr>
<tr>
<td>E</td>
<td>empty</td>
</tr>
</table>
Not optimized, but this should more or less work:
$aFiles = array ("A","B","C","D","E","F","G","H","I","J","K","L","M","N",);
$rows = 4;
$columns = floor((count($aFiles)/$rows))+1;
echo '<table>';
for ($i=0;$i<$rows;$i++) {
echo '<tr>';
for ($j=0;$j<$columns;$j++) {
echo '<td>';
if (isset($aFiles[$i+$j*$rows]))
echo $aFiles[$i+$j*$rows];
else
echo " ";
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
You can change the number of rows if you want.
Try this one. Assume that your $aFiles contains a-z alphabetically.
for ($i = 0; $i < count($aFiles/2); $i++){
echo '<tr><td><a>'.$aFiles[$i].'</a><td><td><a>'.$aFiles[$i+13].'</a><td></tr>'
}
so im trying to create an image gallery that displays a random image in each cell in a 4 column table and automaticly extends as more images are added to the folder and trying to set it so that every time it load it randomizes the images. right it just reads the images in order and on each row it starts over instead of continuing on though the images.
my code:
$file = null;
$fileList = glob("./upload/*.*");
//create table tag
echo '<table border=1 cellspacing=1 cellpadding=2 width=100%>';
//create tr tag
echo '<tr>';
# Print each file
echo "Files found:"; foreach($fileList as $file) {
echo " - ". $file;
echo '<td width="25%"><img src="' . $file . '" width="100%" /></td>'; }
echo '</tr>';
echo '</table>';
that was my first try and it just create a single row
my second attempt:
//create table
echo '<table border=1 cellspacing=1 cellpadding=2 width=100%>';
echo '<tr>';
$x = 1;
$y = 1;
// Display the results
do {
do {
foreach($fileList as $file)
echo '<td width="25%"><img src="' . $file . '" width="100%" /></td>';
$x = $x +1;
$y = $y +1;
}
while ($x <= 3);
do {
foreach($fileList as $file)
echo '<td width="25%"><img src="' . $file . '" width="100%" /></td>';
echo '</tr>';
echo '<tr>';
$x = $x - 4;
$y = $y +1;
}
while ($x = 5);
}
while ($y <= 20);
echo '</tr>';
echo '</table>';
this time it just starts over on every row and create way to many rows
Your foreach loop starts over each time you call it. You should abandon the do/while loops and use for loops instead. One for the rows and one for the columns:
$fileList = glob("./upload/*.*");
echo '<table border=1 cellspacing=1 cellpadding=2 width=100%>'
// Determine max rows:
$max_rows = ceil(count($fileList) / 4);
// Keep an index
$index = 0;
// First loop for rows
for ($row = 0; $row < $max_rows; $row++) {
// Start a new table row
echo '<tr>';
// Second loop for columns
for ($col = 0; $col < 4; $col++) {
if ($index < count($fileList)) {
echo '<td width="25%"><img src="' . $fileList[$index++] . '" width="100%" /></td>';
}
else {
echo '<td></td>';
}
}
echo '</tr>';
}
echo '</table>';