Unexpected behavior with strnatcmp () PHP
I'm trying to get a function to increase alpha upward in PHP, say A-> ZZ or AAA -> ZZZ with all variations in between, i.e. A, B, C ... AA, AB, AC..ZX, ZY, ZZ etc.
The following code works sometimes but then breaks in certain cases, this example works great.
$from = "A";
$to = "ZZ";
while(strnatcmp($from, $to) <= 0) {
echo $from++;
}
It doesn't work as expected yet.
$from = "A";
$to = "BB";
while(strnatcmp($from, $to) <= 0) {
echo $from++;
}
Output:
First: A B C D .. AA AB AC .. ZX ZY ZZ
Second: A B
Does anyone know what's going on here? or maybe a different approach to my problem. Thanks to
source to share
It works, but it stops at BA
... so you can say $to = 'BC';
or you can throw in $to++;
right after the announcement $to
.
$from= 'A';
$to = 'BB';
while ($from !== $to) {
echo $from++;
}
$from= 'A';
$to = 'BB';
$to++;
while ($from !== $to) {
echo $from++;
}
If you are 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;
}
source to share
This should work for you:
<?php
$from = "AA";
$to = "BB";
while(strnatcmp($from, $to) <= 0)
echo $from++ . "<br />";
?>
Output:
AA...BB
If you want to create the alphabet first, then copy it before the code above:
$from = "A";
$to = "Z";
while(strnatcmp($from, $to) <= 0)
echo $from++ . "<br />";
source to share