简体   繁体   中英

php how to loop z to a?

i was read this document document

they can loop from A to Z with this code.

$string = 'A';
for ( $i = 0; $i<=1; $i++ ) {
    echo $string;
    ++$string;
}

and result can go from A to B or more than this up to $i

but!!

i can't do loop from Z to A with this code

--$string;

Does anyone know how to loop from Z to A?

ps1. i can't use range(); because 'Z' is in variable.

ps2. this is excel column that can go from A to Z, AA, AB or more then this.. so, i can't use variable in range or number to character.

You can try

$range = range("Z", "A");
foreach ( $range as $chr ) {
    echo $chr;
}

Output

ZYXWVUTSRQPONMLKJIHGFEDCBA

If you must start with Z

$s = 'Z';
while($s != "@"){
    print($s) and $s = chr(ord($s) - 1);
}
for($alpha = 90; $alpha &gt;= 65; $alpha--) {
  echo chr($alpha);

}

Decrementing Operators don't work on chars as far as I know.

This workaround should do the trick

$string = 'Z';
for ( $i = 0; $i<=25; $i++ ) {
    echo $string;
    $string = chr(ord($string) - 1);
}

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