cowboybebop
cowboybebop

Reputation: 2345

PHP array error

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

Answers (5)

Ruan Mendes
Ruan Mendes

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

Floern
Floern

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

chaos
chaos

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

bharath
bharath

Reputation: 1233

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

http://codepad.org/r86J8WtQ

Upvotes: 1

shamittomar
shamittomar

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

Related Questions