0

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.

3
  • sorry I was not clear... the array is not numeric... e.g $test['element_1'] Commented Feb 19, 2010 at 15:15
  • Same questions: stackoverflow.com/questions/2230154/… and stackoverflow.com/questions/2236720/… Commented Feb 19, 2010 at 15:31
  • The first question is similar... but its about accessing an array and not writing to it... the second is a completely different question... Commented Feb 19, 2010 at 15:34

4 Answers 4

5

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

If it doesn't have an order, then why are there functions to sort it?
1

does this work?

reset($x);
$x[0] = $value;

1 Comment

The reset isn't actually needed to set the first element.
0

Do you mean prepend the array with a value?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.