Insert space into a PHP variable

Asked

Viewed 2,504 times

-7

Hello I see that it is a very simple question apparently but I am finding a lot of difficulty in doing this, I must probably be looking the wrong way on the subject, what I am trying to do is the following:

$var3 = $var1." ".$var2;

In the case var3 would receive the string var1 + var2 with a space between them, but that way I can’t achieve what I want, any way to do it in this style? (simply).

EDIT: I tested the code and now it worked, probably should have had some error at the time of execution.

  • If $var3 doesn’t get what you want, so what do you want? Isn’t the space between the values of $var1 and $var2?

  • What I want is that it receives the var1 + var2 with a space between them, for example if the content of var1 is car and var2 is plate the result comes out as follows: carroplaca however I want to exit car plate (with space between them).

  • $var1 and $var2 have value?

  • 1

    @Wel Question code generates result without space? Are you absolutely sure about this? Look at this...

  • Try this example: http://php.net/manual/en/language.operators.string.php

  • In my test at least yes (I’m using php version 5 if it makes a difference).

  • 1

    @Wel No, the result is the same, with the space, in all versions, since the 4.3.0, at least. See details.

  • I really tested with the same situation and it worked here.

Show 3 more comments

1 answer

-2


you can use the function sprintf, see:

$var1 = "Olá";
$var2 = "Mundo";
$var3 = sprintf("%s %s", $var1, $var2);
echo $var3; // Olá Mundo

You can use as many parameters as you want in the function sprintf that the PHP will put in sequence you set:

$texto = sprintf("%s %s %s %s", $var1, $var2, "Outra mensagem", "final");
echo $texto; // Olá Mundo Outra mensagem final

See the complete documentation of this function

  • $var3 = "{$var1} {$var2}" makes the code much more readable :D

  • 2

    @Andersoncarloswoss prefer to use the function, I think it is already a custom, so much so that sometimes I use other placeholders as %d, %f and so do not need to keep converting whole to float and etc...

  • I would like to know why -1; Please if you disagree or something is wrong send here in the comments.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.