To create alphabetical list in PHP according to variable number

Asked

Viewed 286 times

1

I need to create a list of letters in alphabetical order, according to the variable $nalternatives, for example:

$alternativas = 3;
aí preciso criar:
a
b
c

If $nalternatives is 2, then it’s just a, b, and so on

How can I do that?

3 answers

1


If the number of alternatives you need is less than the letters of the alphabet, you can do it at the expense of the function range. This function returns an array of all elements ranging from an initial element to a final element defined as function parameters.

Imagining that wanted 3 alternatives fixed form could do so:

$alternativas = range('a', 'c'); 

If the number of alternatives is dynamic you can also use chr and ord to build the final element dynamically. With the ord get the value ASCII of the initial letter, then increase the desired amount and obtain the resulting letter of that number with chr:

$quantidade = 10;
$alternativas = range('a', chr(ord('a') + $quantidade)); 

Exit:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => g
    [7] => h
    [8] => i
    [9] => j
    [10] => k
)

See these small examples in Ideone

0

First you have to have one array with all letters, example:

 $letras = ['a', 'b', 'c', 'd'];

After that, just perform a for to walk the array letter.

Would look like this:

<?php
    $alternativas = 2;
    $letras = ['a', 'b', 'c', 'd'];
    if(count($letras) >= $alternativas) { 
        for($n = 0; $n <= $alternativas - 1 ; $n++) {       
            echo $letras[$n];
        }
    }
?>

Since the first index of an array is always 0, I had to subtract 1 in the loop for to be able to get all index correctly.

With this code, I got the following output:

ab

If I hadn’t subtracted -1, the exit would have been:

abc

-1

I hope that settles your question:

function alternatives($num){

    $letters = array();

    $last = ord('z');

    $letter = ord('a');

    $limit = $letter + $num;

    for($letter = ord('a'); $letter < $limit; $letter++):

        $current = chr($letter);

        $letters[] = $current;

    endfor;

    return implode('<br>', $letters);

}

echo alternatives(3);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.