0

I usually add item to array in PHP by

$a = array();
$a['key'] = 'value';

But it give me a E_NOTICE warning of undefined index.

How to add item to array by Key correctly.

3
  • Is that the only code in the script? Commented May 11, 2012 at 4:19
  • 2
    I doubt that snip of code is the caused of E_NOTICE Commented May 11, 2012 at 4:22
  • You need to post more code, there's obviously nothing wrong with this code. Commented May 11, 2012 at 4:22

3 Answers 3

2

First off, read this. It explains everything about arrays.

Secondly, your code looks fine. Are you sure you are declaring your array properly? Post your exact code - obsfusticating your code by changing names and values does not help - especially since it can easily cover up the error.

Sign up to request clarification or add additional context in comments.

Comments

0

That shouldn't give any warning at all, are you sure the problem isn't with value?

Comments

0

You could add the value to the array by key by doing:

$a = array(
    'key' => 'value',
    'key2' => 'value2'
);

etc etc. This is really only viable if you are creating an array with all the keys known a head of time. You could create an empty array and fill it in with values later on if you want to be super complete and do not have the values a head of time like so:

$a = array(
    'key' => '',
    'key2' => ''
);

$a['key']  = 'value';
$a['key2'] = 'value2';

1 Comment

I don't have prior key name for the array.

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.