tags:

views:

246

answers:

6

PHP.

$a['0']=1;
$a[0]=2;

Which is proper form?

+4  A: 

In the first you would have an array item: Key: 0 Index: 0

In the second example, you have only an index set. Index: 0

$arr = array();
$arr['Hello'] = 'World';   
$arr['YoYo']  = 'Whazzap'; 
$arr[2]       = 'No key';  // Index 2
sshow
In your example there are no indexes 0 and 1, so it's better to eliminate those comments.
Ionuț G. Stan
I thought it would be auto-indexed to <the biggest index> + 1 ?
sshow
there is no "auto indexing" unless you use the $arr[]= syntax.
GoatRider
+8  A: 

In the first example you use a string to index the array which will be a hashtable "under the hood" which is slower. To access the value a "number" is computed from the string to locate the value you stored. This calculation takes time.

The second example is an array based on numbers which is faster. Arrays that use numbers will index the array according to that number. 0 is index 0; 1 is index 1. That is a very efficient way of accessing an array. No complex calculations are needed. The index is just an offset from the start of the array to access the value.

If you only use numbers, then you should use numbers, not strings. It's not a question of form, it's a question of how PHP will optimize your code. Numbers are faster.

However the speed differences are negligible when dealing with small sizes (arrays storing less than <10,000 elements; Thanks Paolo ;)

Jaap Geurts
I think you are overstating the speed differences here. Yes the first one is slower but not drastically or at any sort of level that is making it remotely relevant to an application unless you are doing hundred of thousands of permutations.
Paolo Bergantino
A: 

they are both good, they will both work.

the difference is that on the first, you set the value 1 to a key called '0' on the second example, you set the value 2 on the first element in the array.

do not mix them up accidentally ;)

MiRAGe
+2  A: 

If you plan to increment your keys use the second option. The first one is an associative array which contains the string "0" as the key.

Shocker
+4  A: 
VolkerK
Yes, but try $x['0']='foo'; $x[0]='bar';
GoatRider
Exactly my point. $x['0']='foo'; $x[0]='bar'; var_dump($x); --> [0] => string(3) "bar"
VolkerK
+1  A: 

They are both "proper" but have the different side effects as noted by others.

One other thing I'd point out, if you are just pushing items on to an array, you might prefer this syntax:

$a = array(); $a[] = 1; $a[] = 2; // now $a[0] is 1 and $a[1] is 2.

apinstein