How to create letter list alphabetically in PHP according to variable number

1

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

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

If $ nalternativas is 2, there will only be a, b, and so on.

How can I do this?

    
asked by anonymous 02.10.2018 / 23:03

3 answers

1

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

Imagining that I wanted 3 alternatives fixedly 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 ord , get the ASCII value of the initial letter, then increase the desired quantity and get the resulting letter of that number with chr :

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

Output:

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 little examples on Ideone

    
03.10.2018 / 01:01
0

First you have to have a array with all the letters, for example:

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

After that, just for to go through array of letters.

It 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 from the for loop so that I can get all the indexes correctly.

With this code, I got the following output:

ab

If I had not subtracted -1, the output would be:

abc

    
02.10.2018 / 23:17
-1

I hope this solves 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);
    
02.10.2018 / 23:17