开发者

PHP array error

Say I have an array called a.

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

and another array $b

$b = array(a => $a); Thi开发者_StackOverflow中文版s doesnt work while,

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


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.


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.


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

http://codepad.org/r86J8WtQ


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'.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜