I have the following php code:
$mem=10;
echo "Memory: $mem MB<br>";
Which prints out:
Memory: 10 MB
I would like it to print out:
Memory: 10MB
I can't do this:
echo "Memory: $memMB<br>";
Any ideas how I can do this?
Using concatenation is an easy way:
echo "Memory: ".$mem."MB<br>";
echo "Memory: {$mem}MB<br>";
note that this work even with multi level arrays, or objects.
You can use commas with echo
:
echo "Memory: ", $mem, "MB<br>";
Several ways, but IMHO, the best is:
printf('Memory: %dMB<br>', (int) $mem);//drop the cast if you so desire
That just looks clean, to me. In addition, using formatted output strings allows for a lot more control (ie: printf("Value: %.2f", 123.23213);
will output Value: 123.23
)
Alternatives would be:
echo 'Memory: ', $mem, '<br>';//comma's, because echo is a language construct
echo 'Memory: '.$mem.'<br>';//concatenate if you want
Or: use brackets to disambiguate the expression:
echo "Memory: {$mem}MB <br>";
Use concatenation,
echo 'Memory: '.$mem.'MB<br>';
Or else, this would also work,
echo "Memory: {$mem}MB<br>";
This is to separate your variable from the surrounding text.
<?php
$mem=10;
// you can do this because ther $mem is varibale
echo "Memory: $mem MB<br>";
/*
but here you cannot do this because Here $memMB act as a variable which
you not decleared give an error : Notice: Undefined variable: memMB
*/
echo "Memory: $memMB<br>";
/*
For out put Memory: 10MB
*/
echo "Memory:".$mem."MB"."<br />";
?>