Home > database >  How to put multiple parameters in one $
How to put multiple parameters in one $

Time:04-29

Sorry if this is very obvios

I have the following

$a = 1200.00
$b = 675
$c = 123.00

$d = $a$b$c

How would I properly write $d

I thought it would be

$d = '$a'.'$b'.'$c'

How ever this is not correct

How can I make it so when asking to echo out $d <?php echo $d; ?> it shows: 1200.00675123.00

CodePudding user response:

It's not JS, . will not sum up numbers, but convert it to string

$d = $a . $b . $c;


Please note, that you are working with float numbers, so sometimes instead of 1200.00 you can get 1199.999999999999999999998 and outputting it will trim your .00 part.

That's why you need to use number_format() to output floats in format that you want:

function getFloatStr(float $num) {
    return number_format($num, 2, '.', '');
}

$d = getFloatStr($a) . $b . getFloatStr($c);

Example

CodePudding user response:

You are using ', hence the $a are not read as variable, but as a constant string:

$d = $a . $b . $c;

Will concatenate the three variables.

And since you declare $a, $b and $c as number, they are evaluated as such:

<?php
$a = 1200.00;
$b = 675;
$c = 123.00;

$d1 = $a . $b . $c;
$d2 = '$a' . '$b' . '$c';
$d3 = $a   $b   $c;

echo '<pre>';
echo "d1: ", $d1, "\n"; // d1: 1200675123
echo "d2: ", $d2, "\n"; // d2: $a$b$c
echo "d3: ", $d3, "\n"; // d3: 1998
echo '</pre>'; 

If you want to keep the 00, you will need either to use a formatting function, either to use quote:

printf("printf: %.2f%.0f%.2f\n", $a, $b, $d); // printf: 1200.006750.00

Or:

$a = '1200.00';
$b = '675';
$c = '123.00';
  •  Tags:  
  • php
  • Related