Is there any alternative to using for in php? [closed]

-1

Is there any way to do in php what for does, differently? An alternative method for example, but with the same result you would get when using for .

Example of using for :

for($contador = 0; $contador < 10; $contador++)
{
    echo "O contador agora é: $contador";
}

If it exists, how and what would these ways be?

    
asked by anonymous 03.05.2018 / 22:23

2 answers

5

I do not understand the question well, but if the idea is to have 1 to 10, or from 1 to 100, or from 50 to 200, always based on numbers and incrementing then you can simply use range() of PHP itself , example:

$foo = range(1, 10);

print_r($foo);

Then you can use with foreach or even implode , examples:

foreach

foreach (range(1, 10) as $contador) {
     echo "O contador agora é: {$contador}.";
}

implode

$foo = range(1, 10);

$baz = 'O contador agora é: ';

echo $baz . implode('. ' . $baz, $foo) . '.';

About the range

The range() function of PHP does not generate only numerical array, for example if you do something like:

range('a', 'e');

This will generate an array like this:

array('a', 'b', 'c', 'd', 'e');

And you can do the reverse as well:

range('z', 'a');

This will generate an array like this:

array('a', 'b', 'c', 'd', 'e');

That will generate an array like this:

Array
(
    [0] => z
    [1] => y
    [2] => x
    [3] => w
    [4] => v
    [5] => u
    [6] => t
    [7] => s
    [8] => r
    [9] => q
    [10] => p
)

That is, range works for numbers and letters and you can reverse the order.

    
03.05.2018 / 22:33
4

You can get the same result using the while with a counter and a condition that would be used in for , as follows:

$contador = 0;
while($contador < 10) {
    echo "O contador agora é: " . $contador . "";
    $contador++;
}

Technically, in some pre-compiled languages,% for command is converted to a% while following this command structure above. Anyway, it is still an option.

    
03.05.2018 / 22:37