Jump to content

Associative array - using variable in a key that contains a space


yhbae

Recommended Posts

Hi guys,

 

I have encountered a problem while coding in PHP.

 

Here's the problem:

 

I've used an associative array throughout my code and in some cases, the key of the array contains space. I do realize that if you surround your keys with " this should work fine. Except - I cannot do this because I use variables instead.

 

Here's an example:

 

$fish1 = "Pseudotropheus Acei";

$fish2 = "Pseudotropheus Demasoni";

 

$size[$fish1] = 5;

$size[$fish2] = 6;

 

The problem is that 'size' array will not distinguish between the keys $fish1 and $fish2. It _appears_ to only take the first word "Pseudotropheus" hence presumably mapping both into the same space.

 

Does anyone have any ideas?

 

I tried so far:

 

$size["$fish1"] = 5;

$size['$fish1'] = 5;

$size["'"$fish1"'"] = 5;

$size["\""$fish1"\""] = 5;

 

None of the above works. Other than replacing the space with say '_' (which isn't ideal), I am running out of ideas.

 

Appreciate some feedback. :)

 

What eval does is parse the string you input as if it was in the code.

 

eval("echo 'Hello World';"); // Would print out Hello World.

 

So by doing this: eval("$size[\" " . $fish1 . "\"]");

 

PHP would parse this string: "$size[\"" . $fish1 . "\"]"

 

Then evaluate it as if it were code. Sorry if my explanation is confusing, it's the best i can do.

There should be no problem at all using keys with spaces. Run the following and show us the output:

 

$fish1 = "Pseudotropheus Acei";
$fish2 = "Pseudotropheus Demasoni";

$size[$fish1] = 5;
$size[$fish2] = 6;

var_dump($size);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.