What does [1] => 0 mean in this array?
I know this should be a pretty simple question, but I haven't been able to stumble upon an answer yet.
I have the following array
$qid[0][0]=1;
$qid[1][0]=2;
$qid[2][0]=3;
$qid[3][0]=4;
When I use print_r ($ qid) I get the following
Array (
[0] => Array ( [0] => 1 [1] => 0 )
[1] => Array ( [0] => 2 )
[2] => Array ( [0] => 3 )
[3] => Array ( [0] => 4 )
)
I don't understand [1] => 0
in
[0] => Array ( [0] => 1 [1] => 0 )
If anyone can explain what [1] => 0 means in this array, I would really appreciate it. Thank.
EDIT: It turns out my array was really different from what I wrote above, because it was changed later in the code. Thanks everyone for the great answers. I am still reading them all and trying to understand them (arrays jelly my mind).
source to share
[1] => 0
denotes an array element with a value 0
.
The number in []
is the keys of the array. So [1]
- this is the second element of the numerically indexed array (which starts with [0]
), and the value of the second element ( [1]
) is 0
.
PHP uses =>
both an operator to bind array keys / indices to their values.
So a general explanation of this structure:
Array (
[0] => Array ( [0] => 1 [1] => 0 )
[1] => Array ( [0] => 2 )
[2] => Array ( [0] => 3 )
[3] => Array ( [0] => 4 )
)
The outer array is a numeric index array, and each of its elements is a submatrix. The first one ( [0]
) is an array containing 2 elements, and the rest ( [1] through [3]
) are arrays containing only one single element.
source to share
This two dimensional array is actually a one dimensional array of arrays, so you end up with nesting. A bit [x] => y
simply means that the index of the x
array matters y
.
Now your output in this case doesn't actually match your code, since
$qid[0][0]=1;
$qid[1][0]=2;
$qid[2][0]=3;
$qid[3][0]=4;
print_r($qid);
gives:
Array (
[0] => Array ( [0] => 1 )
[1] => Array ( [0] => 2 )
[2] => Array ( [0] => 3 )
[3] => Array ( [0] => 4 )
)
If you want to get:
Array (
[0] => Array ( [0] => 1 [1] => 0 )
[1] => Array ( [0] => 2 )
[2] => Array ( [0] => 3 )
[3] => Array ( [0] => 4 )
)
(with the first array having two elements) you really need:
$qid[0][0]=1;
$qid[0][1]=0;
$qid[1][0]=2;
$qid[2][0]=3;
$qid[3][0]=4;
print_r($qid);
source to share
You've probably added the second item to $ qid [0] somewhere ($ qid [0] [1] = 0). This code
$qid[0][0]=1;
$qid[1][0]=2;
$qid[2][0]=3;
$qid[3][0]=4;
outputs the correct values for me (without [1] => 0:
Array ( [0] => Array ( [0] => 1 ) [1] => Array ( [0] => 2 ) [2] => Array ( [0] => 3 ) [3] => Array ( [0] => 4 ) )
source to share
Simply put, you have a numeric indexed multidimensional array. http://php.net/manual/en/language.types.array.php should have all the information you need to read.
As for why you have [1] => 0
, you need to dig a little deeper into your code to find out where it is assigned.
source to share