I want to print series like A,B,C ......AB
or T,U,V,.....AB
or BA,BB,BC,.....CA

in series i will input start and end characters
can anybody give me logic
Thanks

Dani AI

Generated

As discovered, PHP's string increment operator is a very compact way to walk sequences like A,B,...,Z,AA,AB. 's base-26 remark is worth clarifying: spreadsheet-style column labels treat A as 1 (A=1, Z=26, AA=27), so "A" and "AA" are not the same. The ++ trick is convenient, but it has gotchas: it preserves case (so "Z" -> "AA" but "z" -> "aa"), it behaves specially for non-letter characters, and a naive loop can hang if the start is after the end.

A more robust and predictable approach is to convert labels to integers, iterate numerically, then convert back. The helper functions below implement that (works for arbitrarily long labels, validates alphabetic input and normalizes case):

<?php
function col_to_num($s) {
    $s = strtoupper($s);
    if (!ctype_alpha($s)) return false;
    $n = 0;
    for ($i = 0, $L = strlen($s); $i < $L; $i++) {
        $n = $n * 26 + (ord($s[$i]) - ord('A') + 1);
    }
    return $n;
}

function num_to_col($n) {
    if ($n < 1) return false;
    $col = '';
    while ($n > 0) {
        $n--; // shift so 1 -> 0
        $col = chr($n % 26 + ord('A')) . $col;
        $n = (int)($n / 26);
    }
    return $col;
}

function alpha_range($start, $end) {
    $s = strtoupper($start);
    $e = strtoupper($end);
    if (!ctype_alpha($s) || !ctype_alpha($e)) return array();
    $sn = col_to_num($s);
    $en = col_to_num($e);
    if ($sn === false || $en === false || $sn > $en) return array();
    $out = array();
    for ($i = $sn; $i <= $en; $i++) $out[] = num_to_col($i);
    return $out;
}

// Example: implode(', ', alpha_range('T', 'AB'));
?>

Notes: this method is predictable for comparisons and boundary checks, and avoids PHP++ quirks. For very large ranges (many thousands of labels) consider streaming output rather than building a huge array. If the compact ++ form is preferred for brevity, normalize case first and use a loop that checks equality after emitting the current value to avoid off-by-one or infinite-loop issues.

Recommended Answers

All 3 Replies

Member Avatar for Member #120589

Strangely, I was working on an alphabetic base convertor recently.

What have you tried? - show your code

<?
$char='T';
$lastchar="AR";
$last=++$lastchar;
for($l=$char;$l!=$last;$l++){
    echo $l;
}
?>

I have done.
Thanks

Member Avatar for Member #120589

Yep, I think that's as good as it can get :)

I'm assuming though that you allow A and AA and AAA as distinct entities. If you were using base26 (purely alphabetical and not alphanumeric), they would all be equivalent (i.e. = 0).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.