Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Simple:

for ($i=A;$i<L;){  // remove loop increment                 
    echo $i;
    echo '->';
    echo ++$i;
    echo ', ';
}

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top