While loop output one digit per loop at the same position - php

echo "counter: ";
$i=1;
while ($i <= 5) {
print($i);
sleep(1);
$i++;
}
The above will output: counter: 12345 I need to output eg.: loop 3 - counter: 3 (one digit per loop)
How to do it:
1) When running in a browser?
2) When running from command line (php index.php)?

I think you want to make an auto-updated string. It's impossible to make it with only PHP. You should use Javascript (or a library like jQuery) and send the data from PHP via Ajax call.
You can even do this only with Javascript.
var counter = 1;
setInterval(function () {
counter++;
}, 5);
For command line you can use your code with "\r" at the end of the string.
$i=0;
while ($i <= 5) {
sleep(1);
$i++;
echo "counter: $i\r";
}

I think this is what you need. The counter string was brought inside the loop and a break was added for a new line simulation. Also the < was changed to <= as the loop was running for 4 times instead of 1.
$i=1;
while ($i <= 5) {
print("counter: $i <br>");
sleep(1);
$i++;
}

Related

Run a call every few sec using php

I have around 900 combinations which need to check through an external party for validation.I need to perform below-mentioned steps :
Step 1 : Insert all 900 combinations in table [DONE]
Now I need to do this
Step 2: Run a call every few secs (add PHP wait function)
Step 3: store the result in the DB
so that if something fails, we can start it again from where it failed
Tried php code :
$t0 = microtime(true);
$i = 0;
do{
$dt = round(microtime(true)-$t0);
if($dt!= $i){
$i = $dt;
if(($i % 2) == 0) //every 2 seconds
echo $i.PHP_EOL;
}
}
while($dt<10); //max execution time
Cannot use setInterval in javascript.
I usually use sleep(2). In case you want more granular you can use time_nanosleep
Please also find an example how to make chunks in php.
$arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
$chunked = array_chunk($arr, 5);
$res = [];
$flag = 0;
foreach($chunked as $arr){
sleep(2);
echo 'sleep';
foreach ($arr as $val) {
var_dump($val);
}
}

PHP even numbers generating

I'm somewhat new to PHP, been reading a few books and I've never seen a loop where it gets you all the even numbers(for example from 1 to 10), so I decided to try it myself:
for($i=0;$i<10 && $i % 2===0;$i++)
echo $i;
Tried with only double == as well.
And this,
$i=0;
do echo $i; while($i++<10 && $i % 2 ==0);
Can't seem to figure out how to use 2 conditions in the same statement.
Would appreciate the help!
Thanks.
Try to use this code
for( $i=0; $i<=10; $i++ )
{
if( $i%2 == 0 ){
echo $i;
}
}
The loop is breaking entirely when the second condition fails the first time. On the first iteration: 0 is less than 10, and it is even, so the loop iterates. On the second iteration: 1 is less than 10, but is odd, so the loop breaks.
Your code is the equivalent of this:
for($i=0; $i<10; $i++) {
if ($i % 2 !==0 ) {
break;
}
echo $i;
}
0
You can eliminate the second condition of your for loop to prevent the breakage and rely exclusive on a third expression to increment $i by two each iteration.
for($i=0; $i<10; $i = $i + 2) {
echo $i;
}
02468
The second statement in a for-loop is/are the condition(s) which gets checked every loop. so if it fails your loop stops. what you need will look somewhat like this:
for ($i = 0; $i < 10; $i++)
if ($i % 2 == 0)
echo $i;
So the loop will run over every number but only print out the even ones.
You don't need to loop.
Range can create a range with third parameter step 2.
$arr = range(0,20,2);
Echo implode(" ", $arr);
https://3v4l.org/S3JWV
you can use also regular loop and get the evens by formula:
for($i=0; $i<10 ;$i++) {
$j = $i * 2;
// do somthing with $j witch loop over 10 first evens...
}

PHP Is it possible to skip two or more iterations?

I am aware we can skip the next iteration with continue in a for loop. Anyway to skip the next x loops (2 or more)?
You actually can't, you can do a dirty trick like
for ($i=0; $i<99; $i++){
if(someCondition) {
$i = $i + N; // This will sum N+1 because of the $i++ in the for iterator (that fire when the new loop starts)
continue;
}
}
If you're iterating with a for loop (as opposed to a foreach loop) you could do something like this:
for ($i=0; $i<$numLoops; $i++) {
if(condition()) {
$i+= $numLoopsToSkip;
continue;
}
}
Take for example, you can define the amount of times you want to loop as you want as $y
<?php
y = 5;
while (true) {
// do something
if (y > 0) {
y--;
continue;
}
// do something else
}
?>
Coming soon in PHP 'X' ;-)
continue += x;

No output from the loop

I'm iterating over a huge array and it involves querying multiple APIs so to avoid data loss and timeout, I'm doing this:
for ($i = 0; $i < $count; $i++) {
if ($i % 100 == 0) {
echo 'processed: '.$i."\n";
// save to file
}
}
... it works if the loop is a few hundred iterations during test and outputs processed ..., but nothing at all in prod environment during the script is running, it echos everything only after its done. I just want to avoid any timeouts incase it takes (and usually does) long.
PHP output is buffered; see here. If you flush the buffer (or turn buffering off), you'll see it happen in real-time.
As "belt and braces", if you really care about the output, I'd echo the $count before you even enter the loop.
what is the aim of this code block?
well, until $i reaches 100, it is waste of resource anyway..
you can try:
if( $count > 100 ) {
ini_set('max_execution_time', 0); // no time limit
// $count contains at least $i times 100
for($i = 1; $i <= $count / 100; $i++) {
echo $i * 100;
}
}

PHP Explode function. If function

Could someone help suggest in below php explode function, we are displaying script after 5th listing. How is it possible to display script exactly after 5th listing and 10th listing on a page which has more than 10 listings
We tried using
if ($i == 5 & $i== 10)
but it does not work
Below is original code - which displays script after 5th listing
<?php
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 0; $i < $numberOfListings; ++$i)
{
if ($i == 5)
{ ?>
<script> </script>
<?php }
echo $listings[$i] . "<hr/>";
}
?>
Edit
How is it like - if have to display a separate script on $i==9, could you advise.
Because $i starts at 0 (0 to 9 is 10, whilst 0 to 10 is 11). Try if ($i == 4 || $i== 9), with an or operator.
Also I would not use the && (the and operator), because it is unlikely $i will ever equal both 4 and 9. I'd suggest you read into Truth Tables (and maybe Propositional Calculus) because from seeing what you had tried originally, it would be helpful to understand how a truth table works.
(source: wlc.edu)
You can use the contine, continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
$arr = range(0,9);
foreach($arr as $number) {
if($number < 5) {
continue;
}
print $number;
}
Ref: http://php.net/manual/en/control-structures.continue.php
Try using modulus operator
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 1; $i < $numberOfListings; ++$i)
{
if ($i%5 == 0)
{
echo "in";
?>
<script> </script>
<?php
}
echo $listings[$i-1] . "<hr/>";
}
Here we are looping from 1 and there for $i <= $numberOfListings
and while listing we will use $listings[$i-1]
DEMO CODE AT http://codepad.viper-7.com/lrTOgP

Categories