Reputation: 12042
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. Can anyone explain the code?
Upvotes: 0
Views: 162
Reputation: 3218
Of course value 2 is missing. 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. And the result the value 2 is override by the value 5
Upvotes: 0
Reputation: 3552
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:
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
)
Upvotes: 1
Reputation: 43552
You already have "problem" with your original array. If you 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
Upvotes: 2
Reputation: 212412
$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
Upvotes: 3