Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative index of array in PHP

Tags:

arrays

php

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?

like image 262
Jeg Bagus Avatar asked Jul 31 '11 13:07

Jeg Bagus


5 Answers

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.

like image 70
Pascal MARTIN Avatar answered Oct 04 '22 22:10

Pascal MARTIN


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.

like image 25
Jeremy Roman Avatar answered Oct 04 '22 23:10

Jeremy Roman


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
like image 25
Sz. Avatar answered Oct 04 '22 22:10

Sz.


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);
like image 27
bugos Avatar answered Oct 04 '22 23:10

bugos


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

like image 20
Rain Avatar answered Oct 05 '22 00:10

Rain