2

This seem so simple, and yet I can't find a solution anywhere.

What I want to do is add the contents (r-value) of a variable to an associative array instead of a reference to the variable.

For example, I want this:

$myStr1 = "sometext";
$myStr2 = "someothertext";

$myArray = array(
    "key1"=>$myStr1,
    "key2"=>$myStr2
);

echo($myArray["key1"]);

To produce this:

"sometext"

Instead of this:

"1"        // why??

Any help would be appreciated.

EDIT:

The above works; my bad. Here's the real problem - my $myStr1 variable isn't just assiged a string literal like in the above; it's created using the following syntax:

$myStr1 = "sometext" + anObject->intProperty + "moretext";

Basically I use the + to concatenate various types into a string. Maybe + isn't doing what I think it's doing?

EDIT:

It was definitely the + operator. I casted all non-strings to strings and used . to concatenate instead.

8
  • 5
    ideone.com/ywwma --- your code works as expected Commented Jul 19, 2012 at 2:07
  • Crap. Well I guess I have some investigative work to do. Thanks for pointing this out. Commented Jul 19, 2012 at 2:12
  • What PHP version are you using? Commented Jul 19, 2012 at 2:16
  • @ShaquinTrifonoff I'm using 5.4.3. Commented Jul 19, 2012 at 2:21
  • 1
    For the record the + operator in PHP only performs additions, and if you use it with strings it will just try to cast the strings to values (1) and add them. (just in case it was still unclear) Commented Jul 19, 2012 at 3:20

2 Answers 2

1

You've got it correct the first time. Try this:

$myStr1 = "sometext";
$myStr2 = "someothertext";

$myArray = array(
    "key1"=>$myStr1,
    "key2"=>$myStr2
);

unset($myStr1);

echo($myArray["key1"]);

Even though we unset() the $myStr1 variable, it still echoed sometext.

It should be noted that while it is possible to set $myStr1 by reference, it's not the default.

Sign up to request clarification or add additional context in comments.

4 Comments

Your answer is the same as the other one, plus the comment.
&"sometext"; - it's not valid php. Only variables can be passed by reference
@ShaquinTrifonoff in other words, I provide an actual answer, instead of a comment in answer form?
@zerkms noted, thanks. Momentary brain lapse. It's fixed now.
0

Try your code and its result is:

sometext

1 Comment

Even though this may be considered as an answer, I still personally think it would be more suitable to leave it as a comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.