PHP Arrays: Negative Index

We see that arrays in PHP can have heterogenous elements and the elements can be inserted at any position of choice. But what we have seen is the possibility of using positive numbers as index (position). But it is also possible to use negative numbers as index.

Let’s take a look at the example

$months[-1] = "No such month";
echo "-1 Month: ", $months[-1], "n";

$months[-100] = "No such month";
echo "-100 Month: ", $months[-100], "n";

We insert two strings with indices -1 and -100. On executing,

-1 Month: No such month
-100 Month: No such month
array(2) {
  string(13) "No such month"
  string(13) "No such month"

Analyzing the output of var_dump, we see that two elements with indices -100 and -1 are present in the array.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s