PHP Infinite While loop to terminate - php

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;
}

Related

PHP - How deep should I break out of the loops?

I have infinite loop in PHP and need to know the integer after the break in the switch case. Right now I use break 5; but I am now sure if this is right. Could someone tells me how to break out of all of the loops but while (true). I removed the unnecessary code so only the loops are left.
$i = 0;
while (true)
{
// After the break 5 in the switch we should land here again
foreach ($users as $user)
{
while ($i < 10)
{
if (!empty($user))
{
if (isset($user->id))
{
switch($user->id)
{
case 1:
break 5;
default:
break 5; // Need to break out the foreach. So a break five right?
}
}
}
$i++;
}
}
$i=0;
}
The answer is 3, as break ends execution of the current for, foreach, while, do-while or switch structure.
Where break 1 only exists the switch, 2 the while and 3 the foreach and 4 the main while.
But perhaps this is a better method, as you specifically state where to go instead of guessing. You cannot place the goto marker inside a loop, but in your case you can just make it before the loop.
$i = 0;
mybegin:
while (true){
# 1. After the break 3 in the switch we will -not- land here.
# 3. So if you want to start here, you will need to use the goto statement.
foreach ($users as $user){
while ($i < 10){
if (!empty($user)){
if (isset($user->id)){
switch($user->id){
case 1:
break 3;
default:
goto mybegin;
}
}
}
$i++;
}
}
# 2. Using break 3, the code continues here.
$i=0;
}
But I have to say that I never needed that many loops or a goto statement for that matter as there is always a better way.

While/Switch in php

I've been trying to teach myself php and I came across this code (as with all code I try it out myself to get a better understanding etc) but this one doesn't run.
<?php
$i = 0;
while($i++){
switch ($i) {
case 5:
echo "At 5<br />";
break 1;
case 10:
echo "At 10; quitting<br />";
break 2;
default:
break;
}
}
?>
The output is just blank but would i be correct in saying that $i is incremented until it hits 5, at which point switch($i) would go to case 5 at echo "At 5" and then it'll break that switch statement and continue in the while loop incrementing $i till it reaches 10, then it'll repeat the same process and go to echo "At 10; quitting" and the break 2 would leave the switch and while loop?
During all the other values for $i i'm assuming it goes to default and just breaks out of the switch
Thank You.
The problem is this:
$i = 0;
while($i++){
When you do $i++ the variable $i is incremented with one but the value that is returned is still the old value, see the manual on Incrementing/Decrementing operators. So the first time when $i is still 0, the condition evaluates to false and the whole while() loop is never run / your switch is never reached.
To increase first and then return the value, you do:
$i = 0;
while(++$i){
See the example.
Try and make your code more readable by using variables/constants instead of magic numbers and you can also use labels on loops to break/continue on. Here is an example for you:
define("SOMETHING", 5);
define("SOMETHING_ELSE", 10);
$count = 0;
mainLoop:
while($count < 100) { #loop virtually forever
switch(++$count) { #increment and switch on $count in each iteration
case SOMETHING: #$count = 5
#do something here
echo "At 5<br />";
break; #break switch, continue while loop
case SOMETHING_ELSE: #$count = 10
#do something else here
echo "At 10; quitting<br />";
break mainLoop; #break while loop
}
}

PHP: Loop Logic

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++;
}

How can I make a PHP counter?

I know I have done this in Javascript once, but how can I make it in PHP?
Basically I want to do this:
if (empty($counter)){
$counter = 1;
}else{
"plus one to $counter" ($counter++?)
}
But it didn't work when I tried. How would I go about doing this?
Thank you :)
EDIT: This is so I can do:
if ($counter == 10){
echo("Counter is 10!");
}
EDIT:
This is all in a "while()" so that I can count how many times it goes on, because LIMIT will not work for the query I'm currently doing.
why the extra if into the while?
i would do this:
$counter = 0;
while(...)
{
(...)
$counter++;
}
echo $counter;
To increment a given value, attach the increment operator ++ to your integer variable and place it within your while loop directly, without using a conditional expression to check if the variable is set or not.
$counter = 1;
while(...){
echo "plus one to $counter";
$counter++;
}
If your counter is used to determine how many times your code is to be executed then you can place the condtion within your while() expression:
while($counter < 10){
echo "plus one to $counter";
$counter++;
}
echo("Counter is $counter!"); // Outputs: Counter is 10!
You're going to have to learn the basics of how PHP outputs to the screen and the other controls along with it.
if (empty($counter)){
$counter = 1;
}else{
echo 'plus one to $counter';
$counter++;
}
Something along those lines will work for you.
PHP is pretty flexible with what you throw at it. Just remember, statements need a semicolon at the end, and if you want to output to the screen, (in the beginning) you'll be relying on echo statements.
Also, when dealing with echo statements, notice the difference between single quotes and double quotes. Double quotes will process any contained variables:
$counter = 3;
echo "plus one to $counter"; // output: plus one to 3
echo 'plus one to $counter'; // output: plus one to $counter

Run A PHP function only 30% of Time

I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";

Categories