Benn
Benn

Reputation: 5023

How to reverse foreach $key value PHP?

My brain is off , I am using foreach index to assign z-index to elements but I need it to go in reverse order. The last one should be 0 the first one should have highest z-index;

foreach ($array as $key => $layer){


        // css z-index: $key reversed 
}

any help is appreciated

EDIT: well , everyone is going nuts because I asked this question but I did not look for array_reverse thus I posted a question

I asked how to reverse the $key and only one who understood was Sergey Krivov

Upvotes: 2

Views: 4797

Answers (6)

Syamsoul Azrien
Syamsoul Azrien

Reputation: 2742

Just use PHP built-in function: array_reverse

INPUT:

$my_array = Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
)

.

.

If you call array_reverse($my_array);, then the OUTPUT will be:

Array
(
    [0] => five
    [1] => four
    [2] => three
    [3] => two
    [4] => one
)

.

But if you call array_reverse($my_array, TRUE);, then the OUTPUT will be:

Array
(
    [4] => five
    [3] => four
    [2] => three
    [1] => two
    [0] => one
)

.

.

.

As stated in the documentation:

array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : array

array
  The input array.

preserve_keys
  If set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

https://www.php.net/manual/en/function.array-reverse.php

Upvotes: 1

showdev
showdev

Reputation: 29168

Another method of reversing the order of the array keys is to use PHP's array_combine() to reindex the array with keys reversed by array_reverse(), like so:

$data = array_combine( array_reverse(array_keys($data)) , $data );

This reassigns the array keys as a reversed array of the original keys.

INPUT:

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
)

OUTPUT:

Array
(
    [4] => one
    [3] => two
    [2] => three
    [1] => four
    [0] => five
)

View a demonstration here.

Upvotes: 3

Sergey Krivov
Sergey Krivov

Reputation: 372

$layercount = count($array);
foreach ($array as $key => $layer){
    // css z-index: $key reversed
    $zIndex = $layercount - 1 - $key;
}

Upvotes: 5

Amir Hossein Baghernezad
Amir Hossein Baghernezad

Reputation: 4085

Use array_reverse:

<?php
$array = array_reverse($array);
foreach ($array as $key => $layer){


        // css z-index: $key reversed 
}
?>

Upvotes: -2

AbraCadaver
AbraCadaver

Reputation: 78994

Reverse the array?

foreach (array_reverse($array) as $key => $layer){
        // css z-index: $key reversed 
}

Upvotes: 1

Jonathan M
Jonathan M

Reputation: 17451

Use array_reverse():

$my_reversed_array = array_reverse($my_original_array);
foreach ($my_reversed_array as $key => $layer) {
    ...

http://php.net/manual/en/function.array-reverse.php

Upvotes: 5

Related Questions