I didn’t quite understand the question, but if the idea is to have 1 to 10, or 1 to 100, or 50 to 200, always based on numbers and incrementing then you can simply use the range()
of PHP itself, example:
$foo = range(1, 10);
print_r($foo);
Then you can use it 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) . '.';
Over the range
The function range()
PHP does not only generate numeric 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 it backwards too:
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 to say, range
works for numbers and letters and can reverse the order.
It will depend on what exactly you want to do.
– Woss
What are the ways to iterate an array in PHP
– rray
I didn’t understand the question, could you please explain otherwise?
– Guilherme Nascimento
Otherwise, without using the
for
to obtain the same result, with alternative means @Guilhermenascimento– Florida
@Florida experimented
foreach
+range()
?– Guilherme Nascimento
@Guilhermenascimento didn’t, I really don’t know any other way to do it, so I wanted to know how, if it’s possible and how it would be done. The question may not be the best, but all knowledge is welcome.
– Florida
@Florida I did not deny, I even answered to see if it helped something :) - I’ll leave +1 to see if it helps something. I’m thinking of a better way to describe your question to those who know we can reverse these downvotes.
– Guilherme Nascimento
Unfortunately I took a rain of negatives, I expected at least no positive for being something simple, unfortunately I will have to remove. Nothing against who gave -1, but they could at least say the reason, so better questions can be asked. Plus, I really liked the answers, I really learned another way if you do this, which is great. Learning is cool.
– Florida
@Florida, I tried to research something similar here at Sopt and I did not find. In my view the question is clear, although too simple. Perhaps it will help in the future. Intriguing is that there is only one sign, which does not help much to understand the negatives.
– bio
I didn’t give -1, yet I find the question too vague, and that’s probably why. "Is there another way to do this?" but the example is too abstract and the actual intent of the code is unclear, and gives the intender that it will be much more than it is written. Showing what you’re really trying to do would be better and would probably have attracted more positives.
– Isac