vote up 0 vote down star

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.

flag

sorry I was not clear... the array is not numeric... e.g $test['element_1'] – Mark Feb 19 at 15:15
The first question is similar... but its about accessing an array and not writing to it... the second is a completely different question... – Mark Feb 19 at 15:34

4 Answers

vote up 5 vote down check

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;
link|flag
vote up 3 vote down

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.

link|flag
vote up 1 vote down

does this work?

reset($x);
$x[0] = $value;
link|flag
1  
The reset isn't actually needed to set the first element. – Neil Aitken Feb 19 at 15:15
vote up 0 vote down

Do you mean prepend the array with a value?

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

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.