4
for ($i=A;$i<L;$i++){                   
    echo $i;
    echo '->';
    echo ++$i;
    echo ', ';
}

gives me:

A->B, C->D, E->F, G->H, I->J, K->L

what I want is:

A->B, B->C, C->D, D->E, E->F, F->G

What's the simplest way to do this?

pg.
  • 2,503
  • 4
  • 42
  • 67

4 Answers4

7

Simple:

for ($i=A;$i<L;){  // remove loop increment                 
    echo $i;
    echo '->';
    echo ++$i;
    echo ', ';
}
calebds
  • 25,670
  • 9
  • 46
  • 74
3

Use range() to get the alphabet as an array then use a proper int i++ incrementation.

Julien Meilleur
  • 303
  • 1
  • 4
2

How about just copying the value before incrementing it:

for ($i = 'A'; $i < 'L'; $i++) {                   
    $j = $i;
    $j++;
    echo "$i->$j, ";
}

Ps. You really should quote your string constants. Otherwise your logs will be full of warnings like these:

PHP Notice:  Use of undefined constant A - assumed 'A' in - on line 2
PHP Notice:  Use of undefined constant L - assumed 'L' in - on line 2
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
1

As Julien mentioned, range is sexy for this:

$range = range('A', 'L');

// Had to subtract one from loop iteration total, otherwise the $i + 1 
// would throw an undefined index notice
for ($i = 0, $count = count($range); $i < ($count - 1); $i++) {
    echo sprintf('%s->%s,', $range[$i], $range[($i + 1)]);
}

More info on range.

Mike Purcell
  • 19,847
  • 10
  • 52
  • 89