Foreach in PHP reverse process

Asked

Viewed 951 times

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

  • 1

    $i = 100; ...noose... $i--.

  • 1

    Explain better what you want to achieve because this is weird. Why $listagem if you only use the $i?

  • My idea is to assemble a count of records, as it is in list form.. in the order DESC, I would also enumerate in the order DESC

  • If the records come in descending order from the database just use one foreach normal that will already go through the records in reverse order

4 answers

7


I believe that’s it,

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

4

Initialize total item count

$i = count( $listagem );
foreach($listagem as $valor){
    echo $i; // 100, 99, 98, etc
    $i--;
}
  • has to be $i = Count( $listing ) -1; as it is -1 because of the 0 that the array starts

3

In your example it makes no sense to use a foreach, could normally use the for decreasing:

for($index = count($listagem); $index > 0; $index--) {
    echo $index;
}

And if you need to display items from array, in descending order as reported, just access the element:

for($index = count($listagem); $index > 0; $index--) {
    echo $listagem[$index];
}
  • I use foreah() to bring the database results, which are within the array ($listing)

1

I believe the doubt in our friend is not about displaying a variable in a decreasing sequence, but rather the contents of the array in descending order, so if there is an array with the contents:

$listagem = Array(1, 2, 3... 100);

he wants to show off:

100 99 98... 1

For this purpose the instruction itself "foreach" can be used as it will be possible to execute both for simple array and for array that index is named:

$listagem = Array('a' => 1, 'b' => 2, 'c' => 3... '???' => 100);

This should include instruction "array_reverse" so that the foreach (dry the contents as a queue), list the array in reverse order (as a 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 complicated too much with the explanations, and that the resolution is satisfactory the need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.