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
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: