I found some code that uses negative array indices. Then, I try to use it, nothing special happens. It behaves normally. I can retrieve all elements by using a standard foreach
loop.
So, what is the purpose to use those negative indices? And when should I use it?
An array, in PHP, is actually just some kind of an ordered map : you can use integers (positive or negative), but also strings, as keys -- and there will not be much of difference.
Negative array keys have no special meaning in PHP, as (like any other value) they can be the keys of an associative array.
$arr = array(-1 => 5);
echo $arr[-1];
Some of PHP's standard library functions (the ones that expect regular arrays with only natural integer indices), however, take negative offsets to mean "count from the end instead of the beginning". array_slice
is one such example.
From 7.1 onward, we have an important and practical special case, i.e. when using the array syntax to access particular characters of a string from backwards:
$str = "123";
$empty = "";
echo "LAST CHAR of str == '$str[-1]'<br>"; // '3'
echo "LAST CHAR of empty == '$empty[-1]'<br>"; // '', Notice: Uninitialized string offset: -1
Negative array indexes don't have a special meaning (i.e. get the last/second last element etc.) in PHP. To get the last element of an array use:
$last = end($array);
To get the second last add:
$secondLast = prev($array);
Keep in mind that these functions modify the arrays internal pointer. To reset it use:
reset($array);
In PHP 8
:
Any array that has a number n as its first numeric key will use n+1 for its next implicit key, even if n is negative.
So if the first key is negative -33
, the next key will be -32
(not 0
) .. and so on.
See the difference here
https://3v4l.org/8MXq9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With