PHP loop foreach determine 2nd and 3rd iteration - php

How can I detect 2nd and 3rd iteration
Here's what I did but It doesn't give the right answer
$sample_array = array('boom 1','boom 2','boom 3','boom 4','boom 5','boom 6','boom 7');
$separator2 = 0;
$separator3 = 0;
foreach($sample_array as $sample_array_value){
if(++$separator3 % 3 == 0)
{
echo $sample_array_value."<br /><br /> Separator 3 <br /><br />";
}
else if(++$separator2 % 2 == 0)
{
echo $sample_array_value."<br /><br /> Separator 2 <br /><br />";
}
else
{
echo $sample_array_value."<br />";
}
}
the output of that code is:
boom 1
boom 2
Separator 2
boom 3
Separator 3
boom 4
boom 5
Separator 2
boom 6
Separator 3
boom 7
Which is wrong, I need the output to be:
boom 1
boom 2
Separator 2
boom 3
Separator 3
boom 4
Separator 2
boom 5
boom 6
Separator 2
Separator 3
boom 7

You don't need extra variables, since your array is 0-based indexed, you can just use the key. Also you have to change your logic a bit, so that you get your expected output, e.g.
foreach($sample_array as $key => $sample_array_value){
echo $sample_array_value . "<br />";
if(($key + 1) % 2 == 0 && ($key + 1) % 3 == 0)
echo "<br>Separator 2 <br />Separator 3<br /><br />";
elseif(($key + 1) % 2 == 0)
echo "<br>Separator 2 <br /><br />";
elseif(($key + 1) % 3 == 0)
echo "<br>Separator 3 <br /><br />";
}
output:
boom 1
boom 2
Separator 2
boom 3
Separator 3
boom 4
Separator 2
boom 5
boom 6
Separator 2
Separator 3
boom 7

You're suppose to check for 2nd and 3rd outside the if that implements the boom. since you also want the separator to be done after the boom, then bring it down.
$sample_array = array('boom 1','boom 2','boom 3','boom 4','boom 5','boom 6','boom 7');
$separator2 = 0;
$separator3 = 0;
$count = 1;
foreach($sample_array as $sample_array_value){
echo $sample_array_value."<br />";
if($count % 3 == 0)
{
echo "Separator 3 <br />";
}
if($count % 2 == 0)
{
echo "Separator 2 <br /><br />";
}
$count++;
}

Related

What makes this work?

I am trying to use this chunk of code as template, but Im not fully understanding of how one line works. I'll first provide the full chunk, then I'll single out the line I don't understand.
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
if(!file_exists($thumbnail_image)) {
$extension = get_file_extension($thumbnail_image);
if($extension) {
make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
}
}
echo '<img src="',$thumbnail_image,'" />';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
echo '<div class="clear"></div>';
}
else {
echo '<p>There are no images in this gallery.</p>';
}
I understand how everything with the exception of this line works.
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
I know it is getting its value from this line:
$images_per_row = 3;
But what actually makes this work? Im still pretty new to php, and I would like a better understanding of the code Im about to use before I use it.
Any answers at all would be appreciative!
$index % $images_per_row == 0
The % means "mod", example 4 mod 2 = 0.
A % B = the remainder when we divide A by B.
In your script, the condition is met (valued to 'true') when the remainder of $index divided by $images_per_row equals 0, meaning the divisibility of $index by $images_per_row.
Hope it helps!
% is the modulo operator. It divides the two numbers and then returns the remainder after the division.
It is quite easy to understand if you remember your fractions and how to reduce them to their lowest terms.
So, if we make 5 % 2 into a fraction and reduce it:
5 1 (this is the remainder)
--- → 2 ---
2 2
So, 5 % 2 = 1.
If we take 8 % 3 we can do the same thing:
8 2 (this is the remainder)
--- → 2 ---
3 3
So, 8 % 3 = 2.
If there is no remainder, such as in 9 % 3 then you will get 0 back. See:
9 0 (this is the remainder)
--- → 3 ---
3 3
You can write some PHP to see what the values are when doing the modulo operations:
$perRow = 3;
for ($i = 0; $i < 10; $i++) {
echo "$i % $perRow = ", $i % $perRow, ' | ', "$i / $perRow = ", ($i / $perRow), "\n";
}
Output:
0 % 3 = 0 | 0 / 3 = 0
1 % 3 = 1 | 1 / 3 = 0.33333333333333
2 % 3 = 2 | 2 / 3 = 0.66666666666667
3 % 3 = 0 | 3 / 3 = 1
4 % 3 = 1 | 4 / 3 = 1.3333333333333
5 % 3 = 2 | 5 / 3 = 1.6666666666667
6 % 3 = 0 | 6 / 3 = 2
7 % 3 = 1 | 7 / 3 = 2.3333333333333
8 % 3 = 2 | 8 / 3 = 2.6666666666667
9 % 3 = 0 | 9 / 3 = 3

for loop return string 1-30 on the 5th count and 13count from mysql database that matches numbers using php

I've created a for loop to count 1-30 and want to match mysql number columns 1 - 30 with its attach string data column name and display string inside for loop.
Mysql structure:
|-------------|-------------|--------------|
| id | Number | Name |
|-------------|-------------|--------------|
| 90 | 3 | Test Data |
|-------------|-------------|--------------|
tried simular attempts such as:
foreach($db->results() as $result) {
$count = $result->Number;
$results = $result->Name;
}
for($i=1;$i<=30;$i++) {
if($count == $i) {
echo $results;
}else{
echo '';
}
}
Needing help! Thank you!!!
================================================================================================================================================================
Ok here is what I am trying to accomplish... It works with assigning to the correct number when matching (Thanks for the suggestion). Here is what I have:
$name = array();
$number = array();
foreach($forDB->results() as $for){
$name = $for->firstname;
$number = $for->number;
for($i=1;$i<=30;$i++) {
if($i<=5){
if($number == $i) {
echo $i.' = '.$name;
}
} //then the rest of remanding numbers to 30
}
}
this echos:
2 = name1
4 = name4
But what I would like to do is also echo the numbers of $i between the numbers and values as:
1
2 = name1
3
4 = name4
5
So I try this but it appends to each value:
$name = array();
$number = array();
foreach($forDB->results() as $for){
$name = $for->firstname;
$number = $for->number;
for($i=1;$i<=30;$i++) {
if($i<=5){
if($number == $i) {
echo $i.' = '.$name.'<br><br>';
} else {
echo $i.'<br>';
}
} else {
echo $i;
}
}
}
Results:
2
3
4
5
6
7
1
2 = name2
3
4
5
6
7
1
2
3
4 = Jeff
1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7
I think you should initialize your count and name variables before the foreach loop as an array then in the foreach loop fill it up with the results, then iterate through it in the for loop.

PHP Counting Negative Numbers and Bold Only Even Numbers

On a form, I used PHP to display every number from 1 to the entered number. For example, if I enter 10 on the form, it displays 1 2 3 4 5 6 7 8 9 10. Now, I want it to be able to handle negative numbers by counting up to 0 (-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0) and make every even number in the results bold, e.g., 2 4 6 8 10, etc.). I've searched exhaustively for the answers without any luck. How would any of you suggest doing this? My code for the first part is displayed below. Thank you in advance.
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
echo ($counter).'<br>';
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
You can do this
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
if( $counter % 2 == 0 )
{
echo "<strong>" . $counter . "</strong><br />";
}
else
{
echo ($counter).'<br>';
}
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
Solution 1
Ok, some more information about the %. This is a modulo. It gives you back the remaining number if you divide it by the mod number. For example
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1 this because 3 / 2 = 1 and a bit,
you can't divide the last 1 completely by 2. So remain 1
4 % 2 = 0
Solution 2
Like crush said, you can use $counter & 1. What does this do?
If you look at a number bitwise. You want to AND it wit 1.
Bitwise number 2 = 0010 AND it with 0001 and your return will be 0000 (zero).
Bitwise number 3 = 0011 AND it with 0001 and your result will be 0001 (one).
If you ceep that going and only check the last bit, you can see if it is a even number. More about bitwise operations.

PHP foreach if/else Issue

I've been struggling with the following code. What I'm trying to do is count the number of reviews based on the score. The information is being drawn from MYSQL and a calculation is being preformed before entering it to an array there will be a maximum of five results (after formatting). To be counted.
The code I have is as follows:
$myArray = str_split(554);
$newArray = array_count_values($myArray);
foreach ($newArray as $key => $value) {
$reviews_percentage = round($value/3*100);
if (array_key_exists("1",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "1 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("2",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "2 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("3",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "3 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("4",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "4 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("5",$newArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "5 - <strong>0</strong> as a percent its : 0 <br />";
}
}
Which is giving the following result:
1 - 0 as a percent its : 0
2 - 0 as a percent its : 0
3 - 0 as a percent its : 0
5 - 1 as a percent its : 50
5 - 1 as a percent its : 50
1 - 0 as a percent its : 0
2 - 0 as a percent its : 0
3 - 0 as a percent its : 0
4 - 1 as a percent its : 50
4 - 1 as a percent its : 50
I can see its running through the loop twice but cannot work out what I'm doing wrong.
Added Database Structure
|------
|id|date_created|date_updated|ip_address|status|element_3|element_4|element_5|element_6|element_7|element_8|element_9|
|------
|1|2012-06-21 15:22:57|2012-06-21 16:06:04|::1|1|19|10|10|10|10|10|10|
|2|2012-06-21 16:21:23|2012-06-21 16:21:40|::1|1|19|10|9|9|9|10|
|3|2012-06-21 18:14:56|2012-06-21 18:15:19|::1|1|18| 5|5|5|5|5|
UPDATED CODE
$result = mysql_query("SELECT * FROM ap_form_5 WHERE element_1='19'") or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($profile_rows = mysql_fetch_array($result)) {
$feature1 = $profile_rows['element_4'];
$feature2 = $profile_rows['element_5'];
$feature3 = $profile_rows['element_6'];
$feature4 = $profile_rows['element_7'];
$feature5 = $profile_rows['element_8'];
$overalladd = $feature1+$feature2+$feature3+$feature4+$feature5;
$ratingsbar .= floor(round($overalladd/5/2, 15, PHP_ROUND_HALF_DOWN));
$myArray = str_split($ratingsbar);
$arrayCount = array_count_values($myArray);
}
function perc($total,$count){
$ans = (100/$total) * $count;
return($ans);
// this array is only being filled like this to to show my working out (your db will populate this)
$ratings[1]= $arrayCount[0]; // 1 star ratings - 2 votes
$ratings[2]= $arrayCount[1]; // 2 star rating - 1 votes
$ratings[3]= $arrayCount[2]; // 3 star rating - 2 votes
$ratings[4]= $arrayCount[3]; // 4 star rating - 0 votes
$ratings[5]= $arrayCount[4]; // 5 star rating - 5 votes
$total_votes = array_sum($ratings);
$i = 1;
foreach($ratings as $rating){
echo "Stars ".$i.": ".perc($total_votes,$rating)."% $ratings[$i]<br />";
$i ++;
}
?>
Which is now giving the following result
Stars 1: 0%
Stars 2: 0%
Stars 3: 50% 1
Stars 4: 0%
Stars 5: 50% 1
Give this a try?
<?php
$result = mysql_query("SELECT * FROM ap_form_5 WHERE element_1='19'") or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($profile_rows = mysql_fetch_array($result)) {
$total_ratings_this_loop = 0; // empty this before looping
$ratings[1]= $profile_rows['element_4']; // assuming that this field contains 1 star ratings for this product
$ratings[2]= $profile_rows['element_5']; // assuming that this field contains 2 star ratings for this product
$ratings[3]= $profile_rows['element_6']; // assuming that this field contains 3 star ratings for this product
$ratings[4]= $profile_rows['element_7']; // assuming that this field contains 4 star ratings for this product
$ratings[5]= $profile_rows['element_8']; // assuming that this field contains 5 star ratings for this product
$total_ratings_this_loop = array_sum($ratings); // takes all of the ratings for this product and totals them from inside the array
$overalladd = $feature1 + $feature2 + $feature3 + $feature4 + $feature5;
echo "Product ID: 19, has the following ratings<br />";
$i = 1; // empty this before looping
foreach($ratings as $rating_count){
echo $i." star, Rating count: ".$rating.",Percentage:".perc($total_ratings_this_loop,$rating)."%<br />";
$i ++;
}
}
?>
Replace your code with below code and check :
$myArray = str_split($ratingsbar);
$newArray = array_count_values($myArray);
foreach ($myArray as $key => $value) {
$reviews_percentage = round($value/$num_rows*100);
if (array_key_exists("1",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "1 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("2",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "2 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("3",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "3 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("4",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "4 - <strong>0</strong> as a percent its : 0 <br />";
}
if (array_key_exists("5",$myArray)) {
echo "$key - <strong>$value</strong> as a percent its : $reviews_percentage <br />";
}
else {
echo "5 - <strong>0</strong> as a percent its : 0 <br />";
}
}
What I'm trying to do is count the number of reviews based on the
score.
Please show us the database structure filled with minimized example data, and tell us what is your expected result according to that data.
OK, if you would like to create something like this:
then I demostrate, how I would do it, because I still does not understand your logic.
votes table (this means user U voted on product P with S stars):
user_id | product_id | star
1 1 5
2 1 5
3 1 4
4 1 1
sql query for total votes on product 1 is
SELECT star,COUNT(*) as C
FROM votes
WHERE product_id=1
GROUP BY star
the result of this is
star C
1 1
4 1
5 2
to write it out:
$rs = mysql_query("");//put query here
$stars_count = array();
$star_sum = 0;
while($r = mysql_fetch_assoc($rs))
{
$stars_count[$r['star']] = $r['C'];
$star_sum += $r['C'];
}
for($i=5;$i>=1;$i--)
echo "Product 1 was voted $i star: ".
(isset($stars_count[$i])? round($stars_count[$i]/$star_sum*100)."%":"0%").
" (".( isset($stars_count[$i])? $stars_count[$i] : 0 ).")<br>";
result:
Product 1 was voted 5 star: 50% (2)
Product 1 was voted 4 star: 25% (1)
Product 1 was voted 3 star: 0% (0)
Product 1 was voted 2 star: 0% (0)
Product 1 was voted 1 star: 25% (1)

Tournament algorithm in php

I need some help. I want to create one tournament. Let's say I have 6 players. 1 2 3 4 5 6
I want to create some.. lets' say stages... Every player will play 5 matches(number of players - 1), in 5 different stages. In one stage, all the players must appear only once.
For example, with 6 players I want to generate these results:
Squad 1:
1-2
3-4
5-6
Squad 2:
1-3
2-5
4-6
Squad 3:
1-4
2-6
3-5
Squad 4:
1-5
2-4
3-6
Squad 5:
1-6
2-3
4-5
So, in every stage, the matches must be unique, and every player must play with every player.
I want one algorithm that will work even if I want 8 players, or 12, or 16, or 28.
Thanks
<?php
$numplayers = 6;
if ($numplayers % 2 != 0) $numplayers++; // Dummy
for ($round = 0;$round < $numplayers - 1;$round++) {
echo 'Squad ' . ($round+1) . ":\n\n1-";
for ($i = 0;$i < $numplayers-1;$i++) {
if ($i % 2 == 0) {
$player = ($numplayers-2) - ($i/2) - $round;
} else {
$player = ((($i-1)/2) - $round);
}
if ($player < 0) $player += $numplayers - 1;
echo ($player+2);
echo ($i % 2 == 0) ? "\n" : '-';
}
echo "\n\n";
}

Categories