php each 1 and 8 element in 2 iterations - php

I have a loop. I need write to 1 and 8 element a button. How I can do it?
$cnt = 1;
while($r = $now->fetch_assoc()) {
if ($cnt > 6) {
break; //write only 5 elements to 1 iteration
}
if($cnt === 1 || $cnt === 8) { //not working
echo "<button>Send</button>";
}
$cnt++;
}
My condition is now working. How I can do correctly condition to 8 element, which in 2 iterations?
Example, waht I want get:
------Button-------
1) record
2) record
3) record
4) record
5) record
1) record
2) record
3) record
------Button-------
1) record
2) record
....

Maybe I understand your question wrong, but I think that this should achieve it.
$i = 1;
$j = 1;
while($r = $now->fetch_assoc()) {
if ($i > 6) {
$i = 0;
}
if($j === 1 || $j%8 === 0) {
echo "<button>Send</button>";
}
$i++;
$j++;
}

Related

Php level and exp system

How can i make a level system where i have 2 table, one for the level and another for amount of exp earned?
I want to be able to manage the different exp requierments myself, like level 2 will need 340exp and level 3 need 450exp. I dont want to set one exp amount and then multiply it. I want to manage the whole system.
I also want to set default level and max level, and give exp directly to the database column without too much problem (for forum posts etc).
I have seen a few questions here but i find them outdated or just not what im looking for.
PS: sorry for bad english and bad explenation.
I found a realy good solution and was able to rewrite it to work with my setup. if anyone is interested i will leave the original link and my edit of it bellow.
my edit:
<?php
// Connect to your database like you normally do, then get any value into the $count variable
$count = $exp;
if($level == 0){
$lvl = 1;
}else{
$lvl = $level;
}
if ($count >= 12800) { $lvl = 10; }
else if ($count >= 6400) { $lvl = 9; }
else if ($count >= 3200) { $lvl = 8; }
else if ($count >= 1600) { $lvl = 7; }
else if ($count >= 800) { $lvl = 6; }
else if ($count >= 400) { $lvl = 5; }
else if ($count >= 200) { $lvl = 4; }
else if ($count >= 100) { $lvl = 3; }
else if ($count >= 50) { $lvl = 2; }
// Render stars or any graphics/images according to dynamic $lvl number
$stars = "";
$i = 1;
while ($i <= $lvl) {
$stars .= "★";
$i++;
}
echo "level $lvl";
?>
Original link:
https://www.developphp.com/video/PHP/Experience-Level-Evaluation-Programming-Tutorial

A Logical Algorithm In PHP

I'm a beginner learning PHP. I have tried to make a loop that has a different behaviour for both even and odd numbers. I've been playing around with it for a while, yet I still can't get it to work. Has anyone got a solution?
$count = 0;
$mod = $count % 2;
while ($count < 10)
{
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
A silly mistake, mod inside while() loop.
$count = 0;
while ($count < 10) {
$mod = $count % 2; //Here
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
$count = 0;
$mod = $count %2;
Is were your problem is.
You have to use the modulus (%) operator inside the for loop. Also, there is no need to store the value from the use of the modulus operator at all, it can be compared directly inside the for-loop.
for ($count = 0; $count < 10, $count++) {
if ($count % 2 == 0) {
echo "even, ";
} else {
echo "odd, ";
}
}
You can also switch the while to a for like this.
Welcome to PHP.
Edit #1:
As you are getting a new value of $count every execution of the for-loop the old value if $count % 2 will be incorrect. It has to recalculate for every $count. First it checks if 0 is divisible by 2, then onto 1 and so forth. For every value of $count you have to check the divisibility.
In most programming languages you aren't computing a variable onto another, instead you are taking the value of the variable. Like $a = $b + $c; in that case, if you change the value of $b or $c it does not automatically update $a. Instead you have to call $a = $b + $c again. It is the same with % operator.
$count = 0;
while ($count < 10) {
$mod = $count % 2;
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
use for loop instead of while loop
for($count=0;$count<10;$count++)
{
if(($count % 2) == 0)
echo "even,";
else
echo "odd,";
}

foreach() every 4 change output

I have an issue where I don't know for a foreach() loop to change the output on every(x) amount of results.
Here is my foreach() code:
$dir_handle = 'assets/icons/';
foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
$cut = substr($file, -4);
echo '<img id="preload_header" src="assets/icons/' . $file . '" /><br />';
}
How would I get it for that 1-4 have the same result, but then 5-8 have a different result, and then back to 1-4?
You want to do a count in your foreach loop
$count = 1;
foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
//Check if count is between 1 and 4
if($count >= 1 && $count <= 4) {
//Do something
} else { //Otherwise it must be between 5 and 8
//Do something else
//If we are at 8 go back to one otherwise just increase the count by 1
if($count == 8) {
$count = 1;
} else {
$count++;
}
}
}
You can use the % operator, combined with a division by 4:
foreach ($a as $key => $val) {
$phase = $key / 4 % 2;
if ($phase === 0) {
echo 'here';
}
elseif ($phase === 1) {
echo 'there';
}
}
This switches between the two branches every 4 iterations of your loop.
As pointed out in the comments, the above method assumes that the keys of your array are in order. If not, you can add a counter variable in the loop, like:
$c = 0;
foreach ($a as $val) {
$phase = $c++ / 4 % 2;
if ($phase === 0) {
echo 'here';
}
elseif ($phase === 1) {
echo 'there';
}
}

How to generate table with more than 5 conditions

Short
Generating table with barcodes of items. Each item has exact quantity in database table. Fields in tables are limited: 65, if more then 65 then build a second table, then a third one...How to generate tables with this conditions?
Detailed
Let's say we want to generate a table with 65 available fields (5x13).
My plan is the following
User selects items' checkboxes
When user submits form, PHP gets values of checked checkboxes
PHP gets quantities of each item from database
Generating table
For ex. the quantity for item id 55 is 2 and for 56 is 4 then the table must look like that
My code looks like that (I know that it's wrong, but I can't figure out how it must be. There must be more than 5 counters: rows counter, columns counter, $_POST['id'] counter, items' quantity counter, table counter (if total sum is more than 65))
UPDATE
<?php
$items = array();
foreach ($_POST['checkbox'] as $id) {
$stmt = $db->prepare("SELECT `qt` FROM `items` WHERE `id`=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($qt);
$stmt->fetch();
$stmt->close();
for ($cnt = 1; $cnt <= $qt; $cnt++)
$items[] = $id;
}
$i = 0;
foreach ($items as $item) {
for ($j = 0; $j < $item['quantity']; $j++) {
// check if it's the beginning of a new table
if ($i % 65 == 0)
echo '<table>';
// check if it's the beginning of a new row
if ($i % 5 == 0)
echo '<tr>';
echo '<td><img src="bc.php?id=' . $item['id'] . '" alt="' . $item['name'] . '" /></td>';
// check if it's the end of a row
if (($i - 1) % 5 == 0)
echo '</tr>';
// check if it's the end of a table
if (($i - 1) % 65 == 0)
echo '</tr></table>';
$i++;
}
}
// if the last row wasn't closed, close it
if ($i % 5 != 0)
echo '</tr>';
// if the last table wasn't closed, close it
if ($i % 65 != 0)
echo '</table>';
?>
Any suggestion?
EDIT 4
<?php
$i = 0;
foreach ($_POST['checkbox'] as $id) {
$stmt = $db->prepare("SELECT `qt` FROM `items` WHERE `id`=?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($qt);
$stmt->fetch();
$stmt->close();
for ($cnt = 1; $cnt <= $qt; $cnt++) {
// check if it's the beginning of a new table
if ($i % 65 == 0)
echo '<table>';
// check if it's the beginning of a new row
if ($i % 5 == 0)
echo '<tr>';
echo sprintf('<td><img src="bc.php?id=%1$d" alt="%1$d" /></td>', $id);
// check if it's the end of a row
if (($i + 1) % 5 == 0)
echo '</tr>';
// check if it's the end of a table
if (($i + 1) % 65 == 0)
echo '</table>';
$i++;
}
}
// if the last table isn't full, print the remaining cells
if ($i % 65 != 0) {
for ($j = $i%65; $j < 65; $j++) {
if ($j % 65 == 0) echo '<table>';
if ($j % 5 == 0) echo '<tr>';
echo '<td></td>';
if (($j + 1) % 5 == 0) echo '</tr>';
if (($j + 1) % 65 == 0) echo '</table>';
}
}
You need to just repeatedly make sheets of 65 cell tables until you're done.
I'm going to pseudo code:
data rows = resultOfMyQuery();
int index = 0;
while(index < rows.count()) {
index = createASheet(rows, index);
}
END;
int createASheet(data rows, int index) {
int availableCells = 65;
int column = 0;
print("<table>");
while (availableCells > 0) {
if (index < rows.count()) {
data row = rows.get(index);
int quantity = row.getQuantity();
if (quantity > availableCells) {
// Stay on this item with reduced quantity for next sheet.
row.setQuantity(quantity - availableCells);
rows.set(index, row);
} else {
// Move on to next item on this (or next) sheet.
index++;
}
for (i=0; i<quantity && availableCells>0; quantity--) {
column = makeACell(column, StringFormat("<TAG ATTRIB='%d'></TAG>",row.getId()));
availableCells--;
}
} else {
// fill in empty cells
column = makeACell(column, "");
availableCells--;
}
}
print("</table>");
return index;
}
int makeACell(int column, String filling) {
String cell = "";
if (column == 0) {
cell.append("<tr>");
}
cell.append("<td>").append(filling).append("</td>");
if (column == 4) {
cell.append("</tr>");
}
print cell;
return (column+1) % 5;
}
Why don't you use an existing barcode system like QR-codes? These standards offer libraries to build the codes and are readable by various devices.
If you really want to built your own barcode I strongly suggest to use the binary system to store your values. Think about check sums too.

Random number of divs with random number of elements with PHP

I need to generate random number of divs with five items per div (and remaining items in the last div) from random number of $totalItems and also not all the items satisfy $OKItems... Hopefully the code explains better than me.
My problem is that this script generates empty divs with no content in them.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br />' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
echo ($OKItems % 5 == 0 || $i+1 == $totalItems) ? '<br />div close<br />' : '';
}
?>
This is what I might get:
div open
div close
div open
11111
div close
div open
div close
div open
div close
div open
11
div close
And this is what I would have wanted in this case:
div open
11111
div close
div open
11
div close
<?php
const N = 5;
$totalItems = rand(2,30);
$items = array() ;
for ($i = 0; $i < $totalItems; $i++) {
$testValue = rand(0, 1);
if ($testValue != 0) {
$items[] = 1 ;
}
if( N == sizeof($items) || (($i == $totalItems - 1) && 0 < sizeof($items)) ) {
echo "<div>" . join(",", $items) . "</div>";
$items = array() ;
}
}
I think you need a bit more structure to your code.
My approach would be to break it up into several stages, as opposed to trying to do all the logic in the loop that outputs data.
What I'd suggest:
Decide how many items to be tested
Test each item and only copy the ones that pass into a new array
Partition this new array into sets of 5
Output each partition as a div
Code (untested):
// Decide how many items to test
$totalItems = rand(2,30);
// Test these items and add them to an accepted array
$items = Array();
for ($i = 0; $i < $totalItems; $i++) {
$testValue = rand(0, 1);
if ($testValue != 0) { $items[] = "1" }
}
//Partition them into sections
$partitions = array_chunk($items,5);
//Output as divs
foreach($partitions as $partition):
echo 'div open <br />';
foreach($partition as $item):
echo $item . "<br />";
endforeach;
echo 'div close <br />';
endforeach;
When you split up the code into logical steps, it becomes much easier to maintain and debug.
<?php
$OKItems = 0;
$totalItems = rand(2,30);
for ($i = 0; $i < $totalItems; $i++) {
echo ($OKItems == 0 || $OKItems % 5 == 0) ? 'div open<br>' : '';
$testValue = rand(0, 1);
if ($testValue != 0) {
echo '1';
$OKItems++;
}
if($OKItems % 5 == 0 || $i+1 == $totalItems) {
echo '<br>div close<br>';
$OKItems = 0;
}
}
?>
That should be working ;)
I changed your check line for an if function that also resets your $OKItems. The problem you had (i think) was that you got a 0 as the random value and that would keep $OKitems on 5.

Categories