2

Say I have an array called a.

$a = array(1=>'one',2=>'two');

and another array $b

$b = array(a => $a); This doesnt work while,

$b = array(a => array(1=>'one',2=>'two')); works.
3
  • 5
    $b = array('a' => $a); should work; string array keys must be enclosed in quotes Commented Jan 24, 2011 at 17:16
  • 1
    Cannot reproduce. The first one emits a notice "Use of undefined constant a - assumed 'a'", but it works. However, you should use strings (text in quotes ;)), like the others mentioned. Commented Jan 24, 2011 at 17:18
  • My bad. It was a case of mismatched quotes in an instance which I failed to notice. thanks for the tip. Commented Jan 24, 2011 at 17:31

5 Answers 5

8

Enclose the key in quotes like this:

 $b = array('a' => $a);

A key may be either an integer or a string. If the key is a string, it must be enclosed in quotes, which your code is missing.

See the fixed code working in action here.

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

1 Comment

+1, correct. but specifically, non-numeric keys are strings, and must be in quotes. (user already has numeric keys working without quotes, which is fine)
3

Unable to replicate. Both of your examples "work" for me, in the sense that they produce a data structure of:

Array
(
    [a] => Array
        (
            [1] => one
            [2] => two
        )

)

However, you shouldn't be using a as a bareword, i.e. it should be:

$b = array('a' => $a);

Possibly in your actual code this is causing you trouble; I can't say for sure because your made-up example doesn't actually generate the failure.

Comments

1

just tested it it should work, have a look at the link

http://codepad.org/r86J8WtQ

Comments

1

For debugging always set error_reporting(E_ALL);. In your case, the reason why it's not working would be displayed.

You have to quote a => 'a'.

Comments

1

Though shamittomar is correct that you should enclose your string array indexes with quotes, PHP magically turns undefined constants (your strings without quotes) into strings, which creates a warning but still runs your code. I tried all the examples on http://writecodeonline.com/php/ and they worked fine!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.