$var = 123 456 789;
I need the value of this variable to be:
$var = 123,456,789;
Or add a comma after the number:
$var = 123, 456, 789;
I tried this way:
str_replace($var," ","")
$var = 123 456 789;
I need the value of this variable to be:
$var = 123,456,789;
Or add a comma after the number:
$var = 123, 456, 789;
I tried this way:
str_replace($var," ","")
You're almost there. The arguments of the str_replace
function that are in the wrong order.
According to the PHP documentation you can consult here , you need to do the following:
$resultado = str_replace(' ', ',', $var); // resultado: 123,456,789;
// ou
$resultado = str_replace(' ',', ', $var); // resultado: 123, 456, 789;
You can always refer to the PHP reference that indicates related functions and other important content in link
To use STR_REPLACE you need to transform the contents of the variable into a string, so you must leave the numbers in quotation marks. Then you pass to replace the spaces with the commas in str_replace, but then you need to pass the value received from replace to a variable that will store the new value. And then you can even detach with explode.
$var = '123 456 789';
$texto = str_replace( ' ', ', ', $var );
echo $texto;
$array = explode( ',', $texto );
var_dump($array);
One way to not forget the order is:
substituir('este', 'por este', 'neste');
translating to PHP
str_replace(' ', ',', $var)
$ var = 123 456 789; is not number nor string, so it will generate an error in PHP
PHP Parse error: syntax error, unexpected '456' (T_LNUMBER) in source_file
You must enclose it in quotation marks to be treated as a string
$var = "123 456 789";
//errado não vai imprimir nada
echo str_replace($var," ","").PHP_EOL;
//substitui espaço por virgula
echo str_replace(" ",",",$var).PHP_EOL;
//substitui espaço por virgula mais espaço
echo str_replace(" ",", ",$var).PHP_EOL;