Access to variables outside the PHP foreach loop

In some code I'm working on, I noticed that several variables are accessing it because of the outlines foreach.

This can be seen in the codeigniter view files of this particular application.

For example, a file of the form:

<?php
foreach ($items as $row):
endforeach;

// HTML / PHP code...

 <td>
     <?php echo form_checkbox('option_1','1', FALSE); ?>
     <?php echo form_hidden('weight_unit', $row->weight_unit); ?>
 </td>
// etc...

This works (i.e. no errors), but I wonder if this will be considered bad practice, and if so, why? (scope, etc.)

Does anyone have an opinion about this, and should variables be called only inside their respective loops?

Another problem that I noticed is the need for a variable in several parts of the file of the form: should I refactor to have several cycles or should there be one foreach / endforeachand the beginning / end of the file.

Any suggestions are greatly appreciated. Thank.

+3
4

$row , .

, ? , , . , , .

- - :

foreach ($foo as $bar) 
{
  // do something
}
$last_bar = isset($bar) ? $bar : null;

, - $last_bar.

, , -

, .

, .

+2

, , - , .

end().

$row = end($items);
+3

. , ( ), . CI, , - / RS. , . , array_pop, end, .

, , , .

+2

, . , ( ) , foreach foreach ? - $row - .

, , PHP ( , , , $row , ).

:

  • use as few global variables as possible - they are difficult to track, maintain and provide the correct values.
  • minimize the amount of variables and use them only in very clear areas
  • Avoid extreme use cases and so-called functions that are completely unnatural in other languages.
  • last but not least, avoid the principle, if the code is difficult to write, it is difficult to read - this principle will not protect you from work, only hatred of your employees.
+1
source

All Articles