I have the following foreach ():
$i = 1;
foreach($listagem as $valor){
echo $i; // O que vai me retornar: 1, 2, 3, 4, 5, ..., 100
$i++;
}
How do I do the reverse process? I would like to return: 100, 99, 98, 97, ..., 1
I have the following foreach ():
$i = 1;
foreach($listagem as $valor){
echo $i; // O que vai me retornar: 1, 2, 3, 4, 5, ..., 100
$i++;
}
How do I do the reverse process? I would like to return: 100, 99, 98, 97, ..., 1
I think that's it,
$i = 100;
foreach($listagem as $valor){
echo $i; // O que vai me retornar: 100, 99, 98 ...
$i--;
}
Initialize the total item count
$i = count( $listagem );
foreach($listagem as $valor){
echo $i; // 100, 99, 98, etc
$i--;
}
In your example it does not make sense to use a foreach
, you could normally use for
with decrement:
for($index = count($listagem); $index > 0; $index--) {
echo $index;
}
And if you need to display the items from array
, in descending order as reported, just access the item:
for($index = count($listagem); $index > 0; $index--) {
echo $listagem[$index];
}
I think the doubt in our friend is not about displaying a variable in descending sequence, but rather the content of the array in descending order, so if there is an array with the content:
$listagem = Array(1, 2, 3... 100);
he wants to display:
100 99 98... 1
For this purpose, the foreach statement itself can be used, since it will be possible to execute both for single array and array that the index is named:
$listagem = Array('a' => 1, 'b' => 2, 'c' => 3... '???' => 100);
To do this, you must include the " array_reverse " statement so that foreach (which wipes the contents as a queue), list the array in reverse order stack structure), so the code can look like this:
foreach ( array_reverse($listagem) as $valor) {
# Manipupação da variável $valor, ex:
echo print_r($valor, true), '<br />';
}
Or, if you want to use the index:
foreach ( array_reverse($listagem) as $indice => $valor) {
# Manipupação das variáveis $indice e $valor, ex:
echo $indice, ':', print_r($valor, true), '<br />';
}
I hope I have not been too complicated with the explanations, and that the resolution satisfies the need.