简体   繁体   English

我在php array_reverse()函数中得到了奇怪的输出

[英]i'm getting the weird output in php array_reverse() functions

I'm getting the weird output 我得到奇怪的输出

<?php
    $a = array('1000'=>1,2,3,4,'1001'=>5);
    var_dump(array_reverse($a));
?>

and I'm getting the output like this: 我得到这样的输出:

array (size=4)
0 => int 4
1 => int 3
2 => int 5
3 => int 1

value 2 is missing. 值2丢失。 Can anyone explain the code? 谁能解释代码?

$a = array('1000'=>1,2,3,4,'1001'=>5);

means 手段

create key entry 1000 with value 1
create key entry 1000+1 with value 2
create key entry 1000+2 with value 3
create key entry 1000+3 with value 4

then 然后

create key entry 1001 with value 5

which already exists (with value 2), so is overwritten with the new value 已经存在(值2),因此被新值覆盖

You already have "problem" with your original array. 您的原始阵列已经存在“问题”。 If you print_r($a); 如果您print_r($a); you will see : 你会看见 :

Array
(
    [1000] => 1
    [1001] => 5
    [1002] => 3
    [1003] => 4
)

And you can see that you are missing one value, because you overwriting it: 您会看到您缺少一个值,因为您覆盖了它:

Index 1000 set value 1.
Index 1001 set value 2.
Index 1002 set value 3.
Index 1003 set value 4.
Index 1001 set value 5. <--- overwritten index 1001

Your code working correct, you started first value with index (1000) which tell PHP to set following keys from this for example, if we print your array it will be like this: 您的代码工作正确,您从索引(1000)开始了第一个值,例如,它告诉PHP从中设置以下键,如果我们打印您的数组,它将像这样:

Array
(
    [1000] => 1
    [1001] => 5
    [1002] => 3
    [1003] => 4
)

and array reverse produces this: 和数组反向产生此:

Array
(
    [0] => 4
    [1] => 3
    [2] => 5
    [3] => 1
)

preserving the keys with second parameter: 保留带有第二个参数的密钥:

 print_r(array_reverse($a,true));

Array
(
    [1003] => 4
    [1002] => 3
    [1001] => 5
    [1000] => 1
)

Of course value 2 is missing. 当然,缺少值2。 Look at this 看这个

$a = array('1000'=>1,2,3,4,'1001'=>5);

As the next value after value 1 is not have a key, so the default is the next key from value 1. So it should be like this array('1000'=>1,'1001'=>2,'1002'=>3,'1003'=>4) And the last value is 5 which already have the key 1001. So it would override the previous value. 由于值1之后的下一个值没有键,因此默认值是值1中的下一个键。因此应类似于此数组('1000'=> 1,'1001'=> 2,'1002'= > 3,'1003'=> 4)并且最后一个值是5,它已经具有键1001。因此它将覆盖先前的值。 And the result the value 2 is override by the value 5 结果值2被值5覆盖

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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