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. :)

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.