简体   繁体   中英

Unexpected behavior with strnatcmp() PHP

I'm trying to get a function to increment alphas upwards in PHP from say A->ZZ or AAA -> ZZZ with all the variations in between, ie. A, B, C...AA, AB, AC..ZX, ZY, ZZ etc..

The following code works sometimes, but then breaks in certain instances, this example works perfectly.

$from = "A";
$to = "ZZ";

while(strnatcmp($from, $to) <= 0) {           
    echo $from++;
}

While this does not work as expected.

$from = "A";
$to = "BB";

while(strnatcmp($from, $to) <= 0) {
    echo $from++;
}

Output is:

First: A B C D .. AA AB AC .. ZX ZY ZZ
Second: A B

Does any one know what's going on here? or maybe a different approach to my problem. Thanks

This works, but it stops on BA ... so you can either say $to = 'BC'; or you can toss in a $to++; right after you declare $to .

$from= 'A';
$to = 'BB';
while ($from !== $to) {
    echo $from++;
}

$from= 'A';
$to = 'BB';
$to++;
while ($from !== $to) {
    echo $from++;
}

If you're using PHP 5.5 you can use a generator.

function alphaRange($from, $to) {
    ++$to;
    for ($i = $from; $i !== $to; ++$i) {
        yield $i;
    }
}

foreach (alphaRange('A', 'BB') as $char) {
    echo $char;
}

This should work for you:

<?php

    $from = "AA";
    $to = "BB";

    while(strnatcmp($from, $to) <= 0)           
        echo $from++ . "<br />";

?>

The Output is:

AA...BB

If you want the Alphabet first too, then copy this before the code from above:

$from = "A";
$to = "Z";

while(strnatcmp($from, $to) <= 0)           
    echo $from++ . "<br />";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM