开发者

How do I invert my array?

开发者 https://www.devze.com 2023-01-08 19:35 出处:网络
I have an a开发者_开发百科rray that i want to invert how do i do this?This really depends on whether you mean invert or reverse?

I have an a开发者_开发百科rray that i want to invert how do i do this?


This really depends on whether you mean invert or reverse?

If you want to invert your keys with the values then take a look at array_flip http://www.php.net/manual/en/function.array-flip.php

<?php 

$values = array("Item 1","Item 2","Item 3"); 
print_r($values); 

$values = array_flip($values); 
print_r($values); 
?> 

Output:

Array
(
    [0] => Item 1
    [1] => Item 2
    [2] => Item 3
)
Array
(
    [Item 1] => 0
    [Item 2] => 1
    [Item 3] => 2
)
?>

if you want to reverse your array then use array_reverse http://php.net/manual/en/function.array-reverse.php

<?php
$values = array("Item 1","Item 2","Item 3"); 
print_r($values); 

$values = array_reverse($values);
print_r($values);

Output:

Array
(
    [0] => Item 1
    [1] => Item 2
    [2] => Item 3
)
Array
(
    [0] => Item 3
    [1] => Item 2
    [2] => Item 1
)
?>

You may also want to reverse the array but key the values assigned to their keys in that case you will want $values = array_reverse($values, true);


Use array_reverse:

$array_inverted = array_reverse($array);


Another option you my want to consider as well is simply read the array from bottom to top instead of from top to bottom if the situation allows for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消