7

How can I end a variable name in a string without using space or any other special character?

Example is there anything I can put between $num and st to output 1st instead of 1 st

$num = 1;
echo "$num st";

Without using the dot opperator for concatination

Xyz
  • 5,955
  • 5
  • 40
  • 58
nist
  • 1,706
  • 3
  • 16
  • 24

2 Answers2

15

Wrap the name of the variable with braces.

$num = 1;
echo "${num}st";

Or use printf syntax instead of simple interpolation:

$num = 1;
printf("%dst", $num);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Use the concatenating . character:

echo $num . 'st';
Jeroen
  • 13,056
  • 4
  • 42
  • 63
  • The reason I asked this question was becouse concatination is a rather costly opperator and the code become hard to read but thanks anyway – nist Jun 10 '12 at 09:38
  • 3
    That's simply not true, concatenation is actually slightly faster: http://stackoverflow.com/questions/13620/speed-difference-in-using-inline-strings-vs-concatenation-in-php5 (though you shouldn't make a decision based on that speed difference, its negligible) – Jeroen Jun 10 '12 at 09:42
  • Have you actually measured the cost difference between using concatenation and other options such as those posted by Quentin... unless you're talking about concatenating significant numbers of strings that are all several thousands of bytes in length, it's almost immeasurable – Mark Baker Jun 10 '12 at 09:46
  • Well it's not costly in speed but in memory usage. A concatination stores every string and then concatinates them. This leads to that a concatination uses double the memory – nist Jun 10 '12 at 09:47
  • @nist - that memory overhead is temporary, until it's completed the concatenation operation, which is why it's only significant for extremely long strings, and even then it's for the few nanosconds that it takes to execute the concatenation itself. – Mark Baker Jun 10 '12 at 09:51
  • @nist - but if you're concatenating purely to echo, don't. Use comma (,) instead of dot (.) so echo $num , 'st'; and you'll find it's mocroscopically more efficient in both memory and speed (though the difference is microscopic) – Mark Baker Jun 10 '12 at 09:52