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?
    – Paul
    May 11, 2012 at 4:19
  • 2
    I doubt that snip of code is the caused of E_NOTICE
    – deex
    May 11, 2012 at 4:22
  • You need to post more code, there's obviously nothing wrong with this code.
    – laurent
    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.

0

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

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
  • I don't have prior key name for the array.
    – Magic
    May 11, 2012 at 4:40

Your Answer

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

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