Showing posts with label PHP FOR LOOP. Show all posts
Showing posts with label PHP FOR LOOP. Show all posts

Monday, 17 September 2018

PHP for loops with multiple statements in each expression

PHP for loops work in the same way as other programming languages and have a useful feature where each expression between the semi-colons can have multiple statements to be executed when separated by a comma. I found this useful myself when I need to have both a zero based and 1 based index in a loop.

PHP for loops

As in other programming languages, PHP for loops work like this:
for( expression1; expression2; expression3 ) {     
    code to run in the loop
}
where expression1 if executed once at the start of the loop; expression2 determines whether the loop should continue on each iteration; and expression3 is executed at the end of each loop.

Executing multiple statements in each expression

What many people do not realise is that multiple statements can be executed in expression1 and expression3 by separating them with commas. For example in psuedo code:
for( expression1a, expression1b; expression2; expression3a, expression3b ) {
    code to run in the loop
}
In my case, I needed to have both a zero based index and a 1 based index inside the loop. A more obvious way to do this with single expressions would be like so:
for( $i = 0; $i < $max; $i++ ) {
     $j = $i + 1;
     // code to run in the loop
}
The alternative way by putting all the assignments into the for( ) part is like this:
for( $i = 0, $j = 1; $i < $max; $i++, $j++ ) {
    // code to run in the loop
}
See also my other post about PHP for loops and counting arrays.

Related posts:

Wednesday, 12 September 2018

PHP for loops and counting arrays

It's well known that calling count($array) in a for loop in PHP is slower than assigning the count to a variable and using that variable in the for loop instead. However until recently, I wasn't aware that the assignment to a variable can be done in the for loop itself and share this here in this post.

The "wrong" way

The following example loops through an array in the variable $array:
for($i = 0; $i < count($array); $i++) {
    // do something
}
The count() function is called on each loop which adds extra unecessary overhead. Even if the array only has a couple of items in it processing will still take longer than assigning count() to a variable.

The "right" way

Here's one way of doing it the "right" way:
$j = count($array);
for($i = 0; $i < $j ; $i++) {
    // do something
}
The count is now assigned to the variable $j so the function is only called once.
Another way of doing the above is like so:
for($i = 0, $j = count($array); $i < $j ; $i++) {
    // do something
}
The assignment $j = count($array) is part of the for loop, separated by a comma from the $i = 0 assignment. It is only called once at the start of the loop. It is not necesssarily superior to the first "right" example above but it does reduce the number of lines of code by one and means the purpose of the variable is clearly for of the loop.

Benchmarking

Out of interest I created an array with 100 elements and looped through the "wrong" way and the "right" way (and the whole thing 10,000 times for measurement purposes); the "right" way averaged about .20 seconds on my test box and the "wrong" way about .55 seconds.
Obviously these sorts of micro-optimizations aren't really going to have much of an effect on your own website (that .20 vs .55 seconds was looping through the test 10k times, remember) but it is interesting to see the differences.

Related posts:

Tuesday, 28 August 2018

PHP for the loop does not enter the loop

For some reason my for loop is not starting by the looks it seems. I tested it by placing an echo statement inside it and it does not display so there must be something wrong, maybe my syntax but I cannnot see it after looking at it for hours.

Thanks for your time.
echo $completedstaffrows; // value of 5
        echo $completedeventrows; //value of 4
            echo "<br/>";

        //Staff

            //For loop to enter the correct amount of rows as entered in the form
            for ($i=0; $i > $completedstaffrows; $i++)
            {

                //Data not inserted into Staff table, FK given from dropdown on form to insert in linking table

                $staffdata = array
                (
                    'staff_id' => $this->input->post ('staff'.$i),
                    'procedure_id' => $procedurefk,
                    'quantity' => $this->input->post ('staff_quantity'.$i),
                    'quantity_sterilised' => NULL, //not implemented yet
                );

                $inserthumanresource = $this->db->insert ('hr', $staffdata);
                echo "hello world"; // to test if for loop working
            }

        //Events

                //For loop to enter all events rows completed by user
                for ($i=0; $i > $completedeventrows; $i++)
                {

                    //First input into "Medical Supplies" table
                    $medsupplies = array
                    (
                        'name' => $this->input->post ('supplies'.$i),
                        'manufacturer' => "Bruce Industries" //To be implemented
                    );

                        //Insert data into table
                        $insertmeds = $this->db->insert ('med_item', $insertmeds);

                        //Get med supplies foreign key for linking table
                        $medsuppliesfk = $this->db->insert_id();

                    //Then input into table "Event"

                    $eventdata = array
                    (
                        'time' => $this->input->post ('time'.$i),
                        'event' => $this->input->post ('event'.$i),
                        'success' => $this->input->post ('success'.$i),
                        'comment' => $this->input->post ('comment'.$i),
                        'procedure_id' => $procedurefk

                    );
                        //Insert
                        $insertevent = $this->db->insert ('procedure_event', $eventdata);

                        //Get event fk for linking table
                        $eventfk = $this->db->insert_id();

                    //Linking table "Resources"

                    $resourcedata = array
                    (
                        'event_id' => $eventfk,
                        'medical_item_id' => $medsuppliesfk,
                        'quantity' => NULL, //Not implemented yet
                        'unit' => NULL

                    );

                    $insertresource = $this->db->insert ('resources', $resourcedata);


change
for ($i=0; $i > $completedstaffrows; $i++)
to
for ($i=0; $i < $completedstaffrows; $i++)
You want to iterate while i is LESS than the variable amount, not more.

Friday, 19 September 2014

for Loops in PHP

PHP provides C-style for loops. The for loop accepts three arguments:
for (start_expressions; truth_expressions; increment_expressions)
Most commonly, for loops are used with only one expression for each of the start, truth, and increment expressions, which would make the previous syntax table look slightly more familiar.
The start expression is evaluated only once when the loop is reached. Usually it is used to initialize the loop control variable. The truth expression is evaluated in the beginning of every loop iteration. If true, the statements inside the loop will be executed; if false, the loop ends. The increment expression is evaluated at the end of every iteration before the truth expression is evaluated. Usually, it is used to increment the loop control variable, but it can be used for any other purpose as well. Both break and continue behave the same way as they do with while loops. continue causes evaluation of the increment expression before it re-evaluates the truth expression.

Statement

for (expr, expr, …; expr, expr, …; expr, expr, …)
statement
Statement List
for (expr, expr, …; expr, expr, …; expr, expr, …):
statement list
endfor;

Statement

for (expr; expr; expr)
statement
Statement List
for (expr; expr; expr):
statement list
endfor;
Here’s an example:
for ($i = 0; $i < 10; $i++) {
print "The square of $i is " . $i*$i . "\n";
}
The result of running this code is
The square of 0 is 0
The square of 1 is 1
...
The square of 9 is 81
Like in C, it is possible to supply more than one expression for each of the three arguments by using commas to delimit them. The value of each argument is the value of the rightmost expression.
Alternatively, it is also possible not to supply an expression with one or more of the arguments. The value of such an empty argument will be true. For example, the following is an infinite loop:
for (;;) {
print "I'm infinite\n";
}
Tip: PHP doesn’t know how to optimize many kinds of loop invariants. For example, in the following for loop, count($array) will not be optimized to run only once.
for ($i = 0; $i <= count($array); $i++) {
}
It should be rewritten as
$count = count($array);
for ($i = 0; $i <= $count; $i++) {
}
This ensures that you get the best performance during the execution of the loop.

Thursday, 4 September 2014

Loops in PHP

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
  • for - loops through a block of code a specified number of times.
  • while - loops through a block of code if and as long as a specified condition is true.
  • do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true.
  • foreach - loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Syntax

for (initialization; condition; increment)
{
  code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )
{
    $a += 10;
    $b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
  
Syntax
while (condition)
{
    code to be executed;
}

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;

while( $i < 10)
{
   $num--;
   $i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10 and num = 40 

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax

do
{
   code to be executed;
}while (condition);

Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
  $i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value)
{
    code to be executed;

}

Example

Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
<body>

<?php
$i = 0;

while( $i < 10)
{
   $i++;
   if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
  if( $value == 3 )continue;
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5