1

I am trying to learn to write more advanced strings. I know I could do this using three different statements, as such:

<?php
function1();
echo " | ";
function2();
?>

To get a result like this: result1 | result2

(my real world example for this is creating links to previous and next posts in wordpress, such as:

<?php   
previous_post_link( '%link', '< Previous' );
echo ' | ';
next_post_link( '%link', 'Next >' );
?>

)

But, since I am trying to improve, and learn new things, I am trying to write this more cleanly. I know I can use double quotes and curly brackets to insert functions, like this:

<?php
echo "{${function1()}} | {${function2()}}";
?>

But this returns a result like this: result1result2 |

Why does this happen and how can i write this code correctly?

Thanks!

zver
  • 33
  • 3

1 Answers1

3

This is because of the logic as your "clean" example is proceeded by php. Steps are:

  1. Invoke function1(). Function makes immediate output to the screen: "result1"
  2. Invoke function2(). Functions makes immediate output to the screen: "result2". And you already have "result1result2" on the screen
  3. Concatenate returned value of function1(), with " | ", and returned value of function2(), and echo the concatenated string. Returned values are null, as I assume, as your functions do not use return statements. So, output from this step is " | ".
  4. Finally, we have "result1result2 | "
KAGG Design
  • 1,945
  • 8
  • 14
  • ah, thank you for the explanation. So just to be clear: when processing, php first has to read the whole echo string to be able to output it, but while doing so it invokes the functions it finds in the string, and if those functions tell it to print something out, it will print that out before it actually prints out the echo command. and the curly brackets escape during string I used, then outputs the returned value, so in order for that to have worked, function1() and function2() would have to have a return value. – zver Sep 20 '17 at 08:45
  • Yes, it is quite close to what I wrote in my answer. – KAGG Design Sep 20 '17 at 09:29
  • absolutely, it's exactly what you wrote. i'm just trying to wrap my mind around all this. thanks again! – zver Sep 20 '17 at 13:12