Search code examples
phparrayscountalphabet

PHP Count 1 too many on Array as it's 0 based?


I've had this problem a few times now when for looping over an array item.

In this instance I'm generating all 2 letter combinations of the alphabet.

The code works (and I know there's a much easier way of doing it with 2 for loops, but I'm trying something different).

However I have to do count -1 as count() returns the number 26 for the array length, however the 26th item obviously doesn't exist as it's 0 based?

Is there not a version of count() that works on a zero-based basis?

<?php
$alphas = range('a', 'z');

$alphacount = count($alphas);

// Why do I have to do this bit here?
$alphaminus = $alphacount -1;

$a = 0;
for ($i=0;$i<$alphacount;$i++)  {
    $first = $alphas[$a];
    $second = $alphas[$i];
    if ($i === $alphaminus && $a < $alphaminus  ) {
        $i = 0;
        $a ++;
    }
    echo "$first$second<br>";
}
?>

Without $alphaminus = $alphacount -1; I get undefined offset 26?


Solution

  • How about:

    <?php
    $alphas = range('a', 'z');
    
    $alphacount = count($alphas);
    
    $a = 0;
    for ($i=0;$i<$alphacount;$i++)  {
        $first = $alphas[$a];
        $second = $alphas[$i];
        if ($i >= $alphacount && $a < $alphaminus  ) {
            $i = 0;
            $a ++;
        }
        echo "$first$second<br>";
    }
    

    So you don't have to to -1 since you don't like it! :)

    And how about:

    $alphas = range('a', 'z');
    for ($i = 0; $i < count($alphas); $i++) {
        for ($a = 0; $a < count($alphas); $a++) {
            echo "{$alphas[$i]}{$alphas[$a]}\n";
        }
    }
    

    Or forget about arrays! This is more fun :)

        array_walk($alphas, function ($a) use ($alphas) {
            array_walk($alphas, function ($b) use ($a) {
                print "$a$b\n";
            });
        });