For LOOP taking time to execute in PHP - php

I am taking a demo test at codility.com.
I tried the following PHP test code:
function solution($A) {
$min = 0;
$size = count($A)-1;
for($i=0;$i<5;$i++){
if($i=0)
$min=$A[0];
}
return $min;
}
The script takes around 3.03s to execute where they have set the maximum execution time to 2.00s.
And if i comment the FOR LOOP it works properly.
Any idea ?

You are overwritting your $i variable here:
if($i=0)
it should be
if($i==0)

because you have wirte if($i=0) it is assignment operator not comparision operator. make it correct if($i==0)
function solution($A) {
$min = 0;
$size = count($A)-1;
for($i=0;$i<5;$i++){
if($i==0)
$min=$A[0];
}
return $min;
}

Your for loop looks like this:
for($i = 0; $i < 5; $i++)
This means: initialize $i to 0, and until $i is 5 or more, execute the loop and increment $i.
But, you wrote this:
if($i = 0)
To compare $i and 0, you should've used ==, not =. This sets $i to 0. The if is not executed, as 0 is equal to false. Then $i is incremented to 1. 1 is less than 5, so the loop is executed forever.
Use if($i == 0) to fix it.

There is a mistake that everyone has pointed out which is if($i=0) should be if($i==0).
But I have one concern. Why there is a for loop when it is simply returning $min which is $A[0] ?

Related

PHP: How to loop from 100 to 0 by -2 without letting it go infinitely?

what I am trying to achieve here is to be able to loop from 0 to 100 (100, 98, 96, 94 ...) but has to stop at 0. What is doing right now is it passes 0 and -2 -4 which crashes the server. What am I doing wrong?
for ($i = 100; $i <= 100; $i--){
echo $i--;
echo "<br>";
}
Maybe a little explanation would be useful.
The middle part of the for loop $i <= 100 is what makes it infinite. That expression is checked before each iteration of the loop, and the loop will continue as long as that expression evaluates to true.
Since you set $ito 100 in the first section of the loop, and you're doing nothing except making it smaller, it will always be <= 100, forever.
The loop will work fine just the way you have it written if you change the continuation condition.
for ($i = 100; $i >= 0; $i--){
echo $i--;
echo "<br>";
}
That way it will continue until $i is reduced to less than zero, then $i >= 0 will be false, and the loop will end.
The third argument in for loop is what will be executed at the end of the loop. So:
for ($i = 100; $i >= 0; $i -= 2){
echo "$i<br>";
}
Will do the trick
As you can read here https://secure.php.net/manual/en/control-structures.for.php
At the end of each iteration, expr3 is evaluated (executed).
Alternatively:
<?php
foreach(range(100, 0, -2) as $n) {
echo $n;
}
for ($i = 100; $i >= 0; $i-=1){
echo $i--;
echo "<br>";
}
I figured it out somehow. Has been studying JavaScript for a year; Loop is still confusing to me

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

Double equals in for loop?

Why doesn't the double equals work in a PHP for loop? The following works:
$cnt = 5;
for ($z = 0; $z <= $cnt; $z++) {
echo $z."!<br />";
}
But why doesn't this work?
$cnt = 5;
for ($z = 0; $z == $cnt; $z++) {
echo $z."!<br />";
}
The loop executes only if the condition evaluates to true. At the first iteration, $z == $cnt is false, so the loop never executes.
A common loop strategy is to use a sentinel value:
$cnt = 5;
$stop = $cnt + 1;
for ($z = 0; $z != $stop; $z++) {
. . .
}
Note that the comparison is negative (!= or !==). Using a sentinel is usually unnecessary for numerical loop variables (I wouldn't recommend it for your posted code), but is useful for other situations (e.g., when $stop represents null, an illegal value, etc.). It's particularly helpful when the loop variable changes in a pattern that is not easy to characterize succinctly.
because on the first iteration $z != $cnt, so the loop stops immediately.
Let us look at this from the computer's perspective:
If I am a computer this is what you told me to do:
set $cnt = 5;
set $z = 0;
check if $z equals $cnt
if so do whatever is in the loop, then increment $z
Trouble is, 5 does not equal 0 and never will, so the loop will simply be skipped. If you had $cnt = $z+1 inside the loop this would be an infinite loop.
So, you see, == works just fine, it simply doesn't do what you think it should do.
Hope this helps!
A for loop works by looping until a condition is made false. In the first example the loop will execute until z = 5 after that z will not longer be less than or equal to cnt (z starts at 0 and increments through each loop). In the second example you have $z == $cnt as your condition, and since z = 0 and cnt = 5 the loop will stop automatically because the condition is made false. You can use not equals instead like following:
$cnt = 6;
for ($z = 0; $z != $cnt; $z++) {
echo $z."!<br />";
}
The syntax of for is:
for (<init>; <condition>; <increment>)
The loop tests <condition> before each iteration. If it's true, it executes that iteration; if it's false, the loop terminates.
In your case, since $z == $cnt is false before the first iteration, the loop terminates immediately.
To do what you want, invert the test. You also need to bump the end value up by one, since the original version used <=, not <. Note that in both cases, the loop executes $cnt+1 times, because you start from 0.
for ($z = 0; $z != $cnt+1; $z++)

Pre-incrementation vs. post-incrementation

How are they different? Here's what I'm thinking, but I'm not sure....
If you use pre-incrementation, for example in a for loop with ++j, then you are basically saying: "Make a copy of the value of j for use in the loop, then increment j, then go through the statements in the loop with the copy of j." If you are using post-incrementation in the same loop j++, then you are basically saying: "Make a copy of the value of j for use in the loop, then go through the statements in the loop with the copy of j, then increment j."
The reason I'm unsure is because I've created a for loop that multiplies the value of j by 10 and then outputs the result for j=1 through j=12, using both post- and pre-incrementation. The human readable output is exactly the same with post- and pre-incrementation. I'm thinking, 'How are the outputs exactly the same if there isn't some kind of copy operation involved?'
So, I'm guessing the difference between pre- and post-incrementation truly becomes important, in php, when I use references (which act as pointers in php) rather than names for return values? This would be because copies of references aren't made, so pre-incrementation would be: "Increment j, then go through the statements in the loop with the changed value of j, then increment j again...," whereas post-incremetation would look like: "Use the value of j for the statements in the loop, then change the value of j, then go through the loop with the new value of j..."
Pre- or post-incrementing do not magically delay things until later. It's simply inline shorthand.
// pre-increment
$var = 5;
print(++$var); // increments first, then passes value (now 6) to print()
// post-increment
$var = 5;
print($var++); // passes value (still 5) to print(), then increments
Now let's look at a loop.
for ($i = 0; $i < 9; $i++) {
print($i);
}
The last part of the loop declaration (the $i++) is simply the statement to execute after each time through the loop. It "passes" the value to nowhere, then increments it. $i isn't used anywhere at that time. Later when the next statement is executed (print($i);), the value of $i has already increased.
// add 1, then do nothing with $i
for ($i = 0; $i < 9; ++$i) {}
// do nothing with $i, then add 1
for ($i = 0; $i < 9; $i++) {}
Whichever way you do it, $i will be the same within the loop.
If it helps, you can think of them as small routines that kind of do this:
// ++$i
{
$i = $i + 1;
return $i;
}
// $i++
{
return $i;
$i = $i + 1;
}
As I reread your question, I think the confusion is more with how the loop works than how increment operators work. Keeping in mind that the increment is a straightforward, all-at-once operation, here's how third expression in the loop works.
// here's a basic loop
for ($i = 0; $i < 9; $i++) {
// do loop stuff
print($i);
}
// this is exactly what happens
for ($i = 0; $i < 9; ) {
// do loop stuff
print($i);
$i++;
}
Just because that last line can be put in the loop declaration doesn't give it any special powers. There are no references or anything used behind the scenes. The same $i variable is seen both inside and outside the loop. Every statement inside or outside the loop directly looks up the value of $i when necessary. That's it. No funny business.
When doing $x++, you are post-incrementing... This means that the incrementation will only occur after the statement has been evaluated.
So, given the following code:
$x = 10; $y = 0; $z = 5;
$y = $z * $x++;
PHP does this:
$x = 10; $y = 0; $z = 5;
$y = $z * $x++;
// Ignore Post-Increment, Evalutate
$y = $z * $x;
$y = 5 * 10;
// Now Increment x - POST-INCREMENT
$x = $x + 1;
$x = 10 + 1;
$x = 11;
// Continue evaluating statement
$y = 5 * 10;
$y = 50;
When doing ++$x, you are pre-incrementing... This means that the incrementation will occur before the statement is evaluated:
$x = 10; $y = 0; $z = 5;
$y = $z * ++$x;
// Do Pre-Increment
$x = $x + 1;
$x = 10 + 1;
$x = 11;
// Evaluate
$y = $z * $x;
$y = 5 * 11;
$y = 55;
In the case of a for loop in PHP, PHP evaluates a for loop as follows:
for($i = 0; $i < 30; $i++) {
doSomething();
}
// Is evaluated EXACTLY as such by PHP
$i = 0;
while($i < 30) {
doSomething();
$i++;
}
The first expression ($i = 0) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, $i < 30 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, $i++ is evaluated (executed) as an independent expression.
Therefore, post-incrementing or pre-incrementing a variable as the third expression in the loop doesn't have an effect on the behavior of it. In this simple case, both expressions will behave exactly the same.
However, in a complex loop such as the following:
for($i = $j = 0; $i < 30; $i += ++$j) {
$j = getResult($j);
}
Post-incrementing or pre-incrementing $j directly affects the value of $i according to the examples above. In this case, you need to choose exactly what you want to do.
$i = 0;
echo $i++;
echo $i;
$j=0;
echo ++$j;
echo $j;
Pre increment display incremented value. But Post increment display value then increment. About code will output 01 and 11

Categories