简体   繁体   中英

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

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

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

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 .

Reverse the array?

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

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

Use array_reverse :

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM