tags:

views:

74

answers:

4

How to write to the first element of an array?

I know reset can return the first element... but you can not use it to write to it.

+1  A: 

does this work?

reset($x);
$x[0] = $value;
vicatcu
The reset isn't actually needed to set the first element.
Neil Aitken
+5  A: 

Anything wrong with $yourarray[0] = $value ?

If you don't want to overwrite the first element, try "array_unshift":

http://www.php.net/manual/en/function.array-unshift.php

EDIT: ok, use this for non-numerical keys:

reset($yourarray);
$key = key($yourarray);
$yourarray[$key] = $newvalue;
Select0r
A: 

Do you mean prepend the array with a value?

array_unshift() - this is costly, rebuilding the array.

Greg K
+3  A: 

That's called an "associative array" or a "hash". Technically, it doesn't have an order. You may have an item that you've put in first, but that's only incidental.

Alex Mcp