PHP: Loop Logic - php

I realize this is extremely simple but I feel I'm over-looking something.
What I want to screen to display is
RED This is 0.
or
GREEN This is 1.
And for it to alternate back and forth between the displayed text. My logic if fine for alternating between Red and Green, but the "This is 0" and "This is 1" text is not displaying.
Here is my code so far:
<?php
$array = array(0=>"RED",1=>"GREEN");
$a_count = 0;
$count = 0;
while($count<10)
// DO 9 TIMES
{
echo $array[$a_count] . ' ';
//SUDO FOR IMAGE BEING DISPLAYED
while($array[$a_count] == 0)
{
echo "This is 0.<br>";
}
while($array[$a_count] == 1)
{
echo "This is 1<br>";
}
//<----SWITCH BACK AND FORTH---->
if($a_count == 1)
{
$a_count = 0;
}
else
{
$a_count++;
}
//<----------------------------->
$count++;
}
?>
I realize the easiest way to get what I would like is:
<?php
$array = array(0=>"RED",1=>"GREEN");
$a_count = 0;
$count = 0;
while($count<10)
// DO 9 TIMES
{
echo $array[$a_count] . ' ';
//SUDO FOR IMAGE BEING DISPLAYED
//<----SWITCH BACK AND FORTH---->
if($a_count == 1)
{
echo "This is 1<br>";
$a_count = 0;
}
else
{
echo "This is 0.<br>";
$a_count++;
}
//<----------------------------->
$count++;
}
?>
But this code does not contain the logic I need for the continuation of this project.
I would greatly appreciate an answer as to why my first code is not printing "This is 0."
Thank you!

What you are looking for is a mod count.
Change your loop for:
for($i=0;$i<10;$i++){
echo $array[$i%2].' This is '.($i%2);
}
The modulo operator returns the remainder of a division.
See: What are the practical uses of modulus (%) in programming?

Why not something like this:
$colors = array(0 => 'Red', 1 => 'Green');
$idx = 0;
$count = 0;
while($count < 10) {
echo "The color is {$colors['$idx']}<br />";
$count = 1 - $count; // if $count is 1, it becomes 0. if it's 0, it becomes 1
}
Your while() loops are basically totally useless. You're trying to compare the RED and GREEN strings again 0. If either evaluation happens to be true, you'll end up with an infinite loop.

Ignoring the inefficiency of this script, your while loops are comparing against the array's values, not its keys. But fixing this problem will actually expose another - an infinite loop.

You aren't changing the value of $a_count in your while loops, so there is no way for them to end.
The problem is here:
while($array[$a_count] == 0)
{
echo "This is 0.<br>";
}
while($array[$a_count] == 1)
{
echo "This is 1<br>";
}
Once it enters the first loop, it will just keep echoing "This is 0.<br>", as $a_count is unchanging.
It looks like you could change these whiles to ifs to make your code work the way you want. You also probably want to check that $a_count is 0 or 1, rather than $array[$a_count]

Well, in your first example before the while($count<10), have you initilize your values?
If you do, you must have a display like that :
RED This is 0.0
This is 0.0
This is 0.0
This is 0.0
This is 0.0
...
"This is 0.0" is display in a infinite loop.
while($array[$a_count] == 0)
{
echo "This is 0.$count<br>";
}
while($array[$a_count] == 1)
{
echo "This is 1<br>";
}
You must change the value in a while loop.
Other tips, I think you mush take a look at "foreach" php loop. Can be useful for what you want to do. modulos can also help you.

I think probably the easiest way to do this is to just use a switch statement. I feel really silly for not thinking of it before.
while($count<10)
{
echo $array[$a_count] . ' ';
//PSUEDO FOR IMAGE BEING DISPLAYED
switch($a_count):
{
case 1:
echo "This is RED.<br>";
$a_count = 0;
break;
case 0:
echo "This is GREEN.<br>";
$a_count++;
break;
}
$count++;
}

Related

PHP loop over every second element of array [duplicate]

I wanted to echo an image every after 3 post via XML here is my code :
<?php
// URL of the XML feed.
$feed = 'test.xml';
// How many items do we want to display?
//$display = 3;
// Check our XML file exists
if(!file_exists($feed)) {
die('The XML file could not be found!');
}
// First, open the XML file.
$xml = simplexml_load_file($feed);
// Set the counter for counting how many items we've displayed.
$counter = 0;
// Start the loop to display each item.
foreach($xml->post as $post) {
echo '
<div style="float:left; width: 180px; margin-top:20px; margin-bottom:10px;">
image file</a> <div class="design-sample-txt">'. $post->author.'</div></div>
';
// Increase the counter by one.
$counter++;
// Check to display all the items we want to.
if($counter >= 3) {
echo 'image file';
}
//if($counter == $display) {
// Yes. End the loop.
// break;
//}
// No. Continue.
}
?>
here is a sample first 3 are correct but now it doesn't loop idgc.ca/web-design-samples-testing.php
The easiest way is to use the modulus division operator.
if ($counter % 3 == 0) {
echo 'image file';
}
How this works:
Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.
There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.
Going off of #Powerlord's answer,
"There is one catch: 0 % 3 is equal to 0. This could result in
unexpected results if your counter starts at 0."
You can still start your counter at 0 (arrays, querys), but offset it
if (($counter + 1) % 3 == 0) {
echo 'image file';
}
Use the modulo arithmetic operation found here in the PHP manual.
e.g.
$x = 3;
for($i=0; $i<10; $i++)
{
if($i % $x == 0)
{
// display image
}
}
For a more detailed understanding of modulus calculations, click here.
every 3 posts?
if($counter % 3 == 0){
echo IMAGE;
}
You can also do it without modulus. Just reset your counter when it matches.
if($counter == 2) { // matches every 3 iterations
echo 'image-file';
$counter = 0;
}
How about: if(($counter % $display) == 0)
I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.
if ($ucounter % 1000 == 0) { echo '+'; }
It will not work for first position so better solution is :
if ($counter != 0 && $counter % 3 == 0) {
echo 'image file';
}
Check it by yourself. I have tested it for adding class for every 4th element.

How to compare 2 numeric strings

I have 2 strings like this
$s1="32.56.86.90.23";
$s2="11.25.32.90.10";
I need to compare $s1 and $s2 and find if there are 2 or more numbers in common.
I am using this way
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo "YES"; } else {echo "no"; }
Since I need millions values of $s1 and $s2 and the code above seems to be slow, do you know alternative way to execute the work faster ?
I tested it with the following code, one million times, less than 2 seconds on my 3 years old laptop.
Loop 1M times takes no time, most time is used for displaying.
Comment off the display, 1M loops, 0.816432 seconds
Saved the results into a file, ~13.564MB, 0.731708 seconds
ob_start();
$t1 = microtime();
for($i=1; $i<=1000000; $i++) {
$s1="32.56.86.90.23";
$s2="10.25.30.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo $i . " YES<br>"; } else {echo $i . " no<br>"; }
}
$out = ob_get_contents();
ob_end_clean();
var_dump($out);
echo '<p>'.(microtime() - $t1).'</p>';
Try this.
$s1="32.56.86.90.23";
$s2="11.23.32.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
//assuming $s1_ar and $s2_ar both has unique values if not please make them unique
$result_array = array();
$hasMatch = 0;
for($i = 0; $i < count($s1_ar) && $i < count($s2_ar); $i++){
if(!isset($result_array[$s1_ar[$i]])){
$result_array[$s1_ar[$i]] = 1;
}else{
$result_array[$s1_ar[$i]]++;
}
if(!isset($result_array[$s2_ar[$i]])){
$result_array[$s2_ar[$i]] = 1;
}else{
$result_array[$s2_ar[$i]]++;
}
}
foreach($result_array as $result){
if($result >=2) $hasMatch++;
}
if($hasMatch >= 2)
echo "YES";
else
echo "NO";
I think it will solve your purpose.
Looking at: php array_intersect() efficiency
There's mention that array_intersect_key may be more efficient. But really it would be nice to have data and versions to compare results.
$s1 = "2.3.5.7.9.11.13.17";
$s2 = "2.3.4.5.6";
$s1 = array_flip(explode('.', $s1));
$s2 = array_flip(explode('.', $s2));
echo count(array_intersect_key($s1, $s2))>=2 ? 'yes' : 'no';
Output:
yes
I thought of a way to solve this in a 2*n complexity:
We loop one list and create an associative array from it's elements (LIST c) then we loop the second list and look up if the list c contains such an index/key ( c[element] ).
This shall be very light weighted :
$commons = 0;
$s1_fliped = array_flip($s1_ar)
foreach($s2_ar as $s2_el){
if ( isset($s1_fliped[$s2_el]) ){
$commons ++;
}
if($commons >=2) break;
});

Remove the 0 from for results

Currently, I'm messing around with SoundCloud's API and it's returning something that looks like this.
0. HotBox Michael da Vinci Prod Free P.mp3
https://api.soundcloud.com/tracks/373337717/stream?client_id=OURID
1. LSSR Chris P Prod Jake Knight.mp3
https://api.soundcloud.com/tracks/373336760/stream?client_id=OURID
Which is working properly as how the code appears, here it is how I'm printing out the results (very messy but I'm just messing around)
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
print '<br>'; print '<br>';
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
print ''.$i.'. '.$title.'.mp3';
print '<br>';
print $stream = ''.$b2.'?client_id=OURID';
}
Now what I'm wondering is how under every circumstance can we make the 0. return as a 1. and continue counting upwards until reaching the end of the for loop, not removing the 0. data but only changing the number.
I recommend a foreach loop with the $i counter declared in the loop and just increment it as you go.
Untested code:
foreach ($house as $i=>$row){
echo '<br><br>',++$i,'. ',preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title'])),".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
p.s. I've improved the regex pattern and eliminated all single-use variable declarations. You can break this up over many lines if you prefer.
If you want to avoid the first iteration's double break tags...
foreach ($house as $i=>$row){
if($i) echo '<br><br>'; // if $i is not 0
echo ++$i,'. ';
echo preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title']));
echo ".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
Based on the comments and your description of what you are trying to do, it sounds like you just need to add another iteration variable:
# Add another variable
$a = 1;
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
echo '<br><br>';
# Here you have the $a show up starting at 1
echo ''.$a.'. '.$title.'.mp3<br>';
echo $stream = ''.$b2.'?client_id=OURID';
# Auto increment here
$a++;
}

PHP Infinite While loop to terminate

I am new to PHP and I am having trouble with making this infinite while loop work. I am trying to make a infinite while loop generate random numbers between 1 and 10 and to output the cube root of those numbers, as well as terminating the loop when 5 is generated. So far I have the code below and I am not sure where I am going wrong. Any help or guidance will be much appreciated.
$counter = rand(1, 10);
while ($counter==5) {
break;
if ($counter >5 or $counter<5) {
echo sqrt($counter) . "</br>";
}
$counter++;
}
EDIT: I have listened to the advice you guys gave to me below and I noticed some mistakes I had made myself such as "or" becoming "and". However I am still yet to understand why it isn't generating a loop with numbers 1-10 to their powers?
while(true)
{
$counter = rand(1, 10);
if ($counter <=10) {
echo sqrt($counter) . "</br>";
}
if($counter ==5) break;
}
you are breaking the loop WHILE (ongoing) your counter equals 5 and only echo once IF your condition is met.
what you might want to do could look like
while(true)
{
$counter = rand(1 , 10);
#echo stuff
if($counter == 5) break;
}

PHP Loop do some once the loop as finished

I have this PHP loop,
foreach($returnedContent as $k => $v) {
$imageName = str_replace($replaceData, "", $v['contentImageName']);
echo "<a class='contentLink' href='".base_url()."welcome/getFullContent/$v[contentId]'>";
echo "<img src='/media/uploads/".strtolower($v['categoryTitle'])."/".$imageName."_thumb.png' alt='$v[contentTitle]' />";
echo "</a>";
}
Once the lopp has finished I was hoping it would be possible to do loop to print x amount of grey boxes is this possible and if so how, basically if the first loop returns 1 item i need the second loop to print out 11 boxes, if the first one returns 9 items I need the second loop to return 3 boxes.
Make sense? Can anyone help me?
So if you want a total of 12 boxes, set a counter and decrement:
$boxes = 12;
foreach($returnedContent as $k =>$v){
// all your previous stuff
$boxes--;
}
for($i = 0; $i < $boxes; $i++){
// print your box here
}
Depending on your application you may also want to check that the number of items in $returnContent is <= $boxes. If it is greater than $boxes you won't get an error but you will get rows with more than $boxes images.
Just keep a counter and increment it for each loop iteration, then add
for (;$counter < 11; ++$counter) {
do_loop_stuff();
}
Maybe you could do something like this (assuming $returnedContent is numerically indexed):
//count to 12 so we get 12 items
for ($i=0; $i<12; $i++) {
//check if there is an entry to print
if (isset($returnedContent[$i])) {
$v = $returnedContent[$i];
$imageName = str_replace($replaceData, "", $v['contentImageName']);
echo "<a class='contentLink' href='".base_url()."welcome/getFullContent/$v[contentId]'>";
echo "<img src='/media/uploads/".strtolower($v['categoryTitle'])."/".$imageName."_thumb.png' alt='$v[contentTitle]' />";
echo "</a>";
} else {
//draw grey box
}
}
After the first loop, you can do:
for($i = 0; $i < 12 - count($returnedContent); $i++)
{
// print the grey boxes.
}
Hmmm Im not sure Im understanding you but
$c = count($returnedContent);
will get you the amount of items in the variable
then:
$c = (11-$c);
if($c > 0) {
for($i=0;$i<$c;$i++) {
// print gray box
}
}
after the first loop. You could also use a counter variable inside the first loop.
I did interpret the question as "Do something when the loop has finished iterating".
In which case a for/foreach loop isn't the best choice here.
how about
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
//then do whatever else you need to.
?>

Categories