-4

I need to replace my "foreach" with "for", but actually I don't know how. Here is the part of my php code:

$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
    echo "\n\r" . $v->id . "\n\r";
    if (1) {
        $a_view_modl = ArticleView :: model($v->id, $v->id);
        $connection = $a_view_modl->getDbConnection();

Thanks!

Sri
  • 633
  • 2
  • 7
  • 20
Andrii
  • 9
  • 2
  • 7

4 Answers4

2
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
    echo "\n\r" . $v->id . "\n\r";
    if (1) {  //you don't really need this, because it's allways true
        $a_view_modl = ArticleView :: model($v->id, $v->id);
        $connection = $a_view_modl->getDbConnection();

if $orgs is an associative array, it becomes:

$r = "";
$j = 0;
for($i = 0; $i < count($orgs); $i++)
{
    echo "\n\r" . $orgs[$i]->id . "\n\r";
    $a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id);
    $connection = $a_view_modl->getDbConnection();
}

better you do some checks first if you go for this solution.

if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal:

$i++; //if you want the increment afterwards
++$i; //if you want the increment before you read your variable

the same for decrements:

$i--; //decrement after reading the variable
--$i; //decrement before you read the variable
Raphael Müller
  • 2,170
  • 2
  • 13
  • 19
0

A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v. Then $v has the value you are using in the snippet of code.
A for loop does only accept indexed arrays, and no associative arrays.

We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0.

$r = "";
$j = 0;

for ($i = 0; $i < count($orgs); $i++) {
    echo "\n\r" . $orgs[$i]->id . "\n\r";
    if (1) {
        $a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id);
        $connection = $a_view_modl->getDbConnection();
MC Emperor
  • 17,266
  • 13
  • 70
  • 106
0
$r = "";
$j = 0;
for($i = 0 ; $i < count($orgs); $i++)
{
    $v = $orgs[$i];
    echo "\n\r" . $v->id . "\n\r";
    if (1) {
        $a_view_modl = ArticleView :: model($v->id, $v->id);
        $connection = $a_view_modl->getDbConnection();
}
S.Pols
  • 3,365
  • 2
  • 17
  • 42
0
foreach ($orgs as $k => $v) {
    // Your stuff
}

for loop

for ($i = 0; $i < count($orgs); $i++) {
    // Your stuff ... use $orgs[$i];
}
MC Emperor
  • 17,266
  • 13
  • 70
  • 106
Aaska Patel
  • 422
  • 6
  • 21