Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [1] => 0 mean in this array?

Tags:

arrays

php

I know this must be a fairly simple question, but I haven't managed to stumble across 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 someone could explain what [1] => 0 means in this array, I'd greatly appreciate it. Thanks.

EDIT: It turns out that my array was indeed different to what I had written above, because it had been modified later in the code. Thanks everyone for the great answers. I'm still reading over them all and trying to make my mind understand them (Arrays turn my mind to jello).

like image 494
TryHarder Avatar asked Apr 26 '26 10:04

TryHarder


2 Answers

[1] => 0 denotes an array element with the value 0.

The numbers in [] are array keys. So [1] is the second element of a numerically indexed array, (which starts with [0]), and the value of the second element ([1]) is 0.

PHP uses => as an operator to relate array keys/indices to their values.

So an overall 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 numerically indexed array, and each of its elements is a sub-array. The first of them ([0]) is an array containing 2 elements, while the rest of them ([1] through [3]) are arrays containing only one single element.

like image 128
Michael Berkowski Avatar answered Apr 29 '26 00:04

Michael Berkowski


That two-dimensional array is actually a one-dimensional array of arrays, which is why you're getting the nesting. The [x] => y bit simply means that index x of the array has the value 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);

produces:

Array (
    [0] => Array ( [0] => 1 )
    [1] => Array ( [0] => 2 )
    [2] => Array ( [0] => 3 )
    [3] => Array ( [0] => 4 )
) 

If you wanted 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'd actually need:

$qid[0][0]=1;
$qid[0][1]=0;

$qid[1][0]=2;

$qid[2][0]=3;

$qid[3][0]=4;

print_r($qid);
like image 42
paxdiablo Avatar answered Apr 29 '26 00:04

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!