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

4
  • 1
    Yes, you must never use concatenation... even if it gives you the output you need, it's just so evil and wrong Commented Jun 10, 2012 at 9:39
  • @MarkBaker Are you serious or being sarcastic?? Commented Jun 10, 2012 at 9:44
  • Perhaps I needed to be more sarcastic, as it clearly wasn't obvious that I was being so Commented Jun 10, 2012 at 9:48
  • I thought so, but I wasn't sure, seeing as some people definitely have very strong opinions about things like this, strangely enough :) Commented Jun 10, 2012 at 9:51

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I though you had to type "{$num}st". I guess you learn something new every day :)
@RobinCastlin, If you type {$num}st, You'' get {1}st as output, not 1st.
0

Use the concatenating . character:

echo $num . 'st';

6 Comments

The reason I asked this question was becouse concatination is a rather costly opperator and the code become hard to read but thanks anyway
That's simply not true, concatenation is actually slightly faster: stackoverflow.com/questions/13620/… (though you shouldn't make a decision based on that speed difference, its negligible)
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
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 - 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.
|

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.