Reputation: 2345
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.
Upvotes: 2
Views: 5131
Reputation: 92274
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!
Upvotes: 1
Reputation: 33904
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'
.
Upvotes: 1
Reputation: 124297
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.
Upvotes: 3
Reputation: 46692
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.
Upvotes: 8