Foreach in PHP inverse process

2

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

    
asked by anonymous 01.08.2017 / 22:02

4 answers

7

I think that's it,

$i = 100;
foreach($listagem as $valor){
echo $i; // O que vai me retornar: 100, 99, 98 ...
$i--;
}
    
01.08.2017 / 22:05
4

Initialize the total item count

$i = count( $listagem );
foreach($listagem as $valor){
    echo $i; // 100, 99, 98, etc
    $i--;
}
    
01.08.2017 / 22:06
3

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];
}
    
01.08.2017 / 22:17
0

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.

    
06.06.2018 / 15:58