00 Votes

PHP: Create Array with arbitrary Index - Index should not start at 0 and can have Gaps

Question by Guest | 2015-06-08 at 22:47

When creating an array in PHP using the code $arr = array(100, 200, 300), the first element in the array always has the index 0, the second element always has the index 1 and the third element always has the index 2.

Is it also possible to create arrays with custom index values that are not necessarily beginning at 0? Or not to allocate all index positions and eventually have a gap between two or more indices? If this is possible, does someone have an example code for me?

ReplyPositiveNegative
0Best Answer0 Votes

Yes, both things are possible.

I will give you a small example.

$arr = array();
$arr[1] = 'A';
$arr[4] = 'B';

In this code, we are creating an array and we are setting the value "A" to the index 1 and the value "B" to the index 4. With this, the first element does not have the index 0 (instead it is 1) and the indices 2 and 3 are not allocated. So, you can create arrays with arbitrary index values.

$arr = array([1] => 'A', [4] => 'B');

Alternatively, you can also use this notation, this code is creating the same result like it is shown in the first example in only one line of code.
2015-06-09 at 22:50

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.