0
<?php
function dosomething(){
    echo "do\n";
}

$temp="test".dosomething();
echo $temp;
?>

expected result:testdo

but actual result is: do

test%

I know how to change the code to get the expected result. But what i doubt is why the code prints result like this. Can someone explain it?Thanks!

5 Answers 5

3

dosomething is echoing to the screen. Since this runs first "do\n" is printed.

dosomething also doesn't return anything so the second echo is equivalent to echo "test";

In order to use the result of the call you should return it:

function dosomething(){
    return "do\n";
}

Which will behave as you expect.

To clarify. In order to work out what $temp is the function must be run first which prints out "do\n" first.

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

Comments

1

Use return.

function dosomething(){
return "do\n"; }

1 Comment

OP wants: I know how to change the code to get the expected result. But what i doubt is why the code prints result like this. Can someone explain it?
1

Use a return statement instead of echo

function dosomething(){
    return "do\n";
}

2 Comments

OP wants: I know how to change the code to get the expected result. But what i doubt is why the code prints result like this. Can someone explain it?
I guess because your function is executed first, so it prints do, and then it print the var $temp which contains test and the concatenation of the function represented by %. You are not agree ?
0

I'm not sure why people are getting down voted. Their answers are right.

http://codepad.org/nagGXY99

2 Comments

read carefully what OP wants: OP wants: I know how to change the code to get the expected result. But what i doubt is why the code prints result like this. Can someone explain it?
Ah, There aren't any spaces contained inside the quotes. \n doesn't render out in browsers. &nbsp; will but the only thing that \n or \r or \r\n will render out is in emails and other documents which the PHP is generating content for. For instance $foo = 'something'; would return "something" where as $foo = ' something ' ... well you get the idea. You could also include &nbsp; in there but I would recommend against it unless you're directly posting the content to the browser.
0

Try this:

Use return in the calling function. Doing that you will get the string where the function is being called. So function is being replaced by string and 2 strings will then con cat.

-

Thanks

Comments

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.