formatting strings (variable+text) - php

I need to add 2 numbers together.
$num1 = 40;
$num2 = 20;
$num12 = $num1 + ':' + $num2;
For some reason this outputs as 60 and it should be 40:20.
is there some way to format this?

yes there is. use php concatenation (.) not javascript concatenation (+).
$num12 = $num1 . ':' . $num2;

What you are looking for is string concatenation.
In php you need the .-operator , not the +:
$num12 = $num1 . ':' . $num2;

Related

Print a sequence of numbers in PHP with the correct (+/-) sign

I need to print some numbers in a sequence with + and - between them. However, I don't know beforehand which number is going to be positive and which is going to be negative. Currently, I echo them like this:
echo "$a + $b + $c + $d + $e + $f";
Let's say the values of $a to $f are all positive. I will get something like: 5 + 10 + 12 + 18 + 9 + 7.
However, if some of the values are negative, I will get something like 5 + -10 + 12 + -18 + 9 + - 7. The ideal output in this case would have been 5 - 10 + 12 - 18 + 9 - 7.
Please not that I don't want to calculate the final result of addition or subtraction. I just want to print it all on the webpage with correct signs.
I could do so by writing 6 nested if() blocks but that seems like a lot of work and doing it every time will be error prone. Is there anything clever that I can do to output the right sign.
The easiest way would be to correct the operator appearance in the final string:
$s = '5 + -10 + 12 + -18 + 9 + - 7'; // result of interpolation or concatenation
$s = str_replace('+ -', '- ', $s);
// => "5 - 10 + 12 - 18 + 9 - 7"
If this is possible for you, this is as fast as it gets -- no looping (in php), no treating each number one at a time with a conditional. If you loop anyway, I'd recommend #Phils suggestion with array_reduce -- functional style php -- adapted to your needs.
Need to check for each variable manually like this:
echo "$a " . ($b < 0 ? " - " . abs($b) : " + $b") . ($c < 0 ? " - " . abs($c) : " + $c") . ($d < 0 ? " - " . abs($d) : " + $d") . ($e < 0 ? " - " . abs($e) : " + $e") . ($f < 0 ? " - " . abs($f) : " + $f");
you can use php sprintf function.
function formatNum($num){
return sprintf("%+d",$num);
}
or
function formatNum($num) {
$num = (int) $num; // or (float) if you'd rather
return (($num >= 0) ? '+' : '-') . $num; // implicit cast back to string
}
for more detail please read it :- http://php.net/manual/en/function.sprintf.php
try this
$a = 10;
$b=-20;
$text = $a." ".$b;
$text= str_replace(" ", "+", $text);
echo $text;
OUTPUT
10+-20
Put the numbers in an array and use array_reduce to create the string
$numbers = [5, -10, 12, -18, 9, -7];
$first = array_shift($numbers);
echo array_reduce($numbers, function($str, $num) {
return $str . sprintf(' %s %d', $num < 0 ? '-' : '+', abs($num));
}, $first);
Demo ~ https://eval.in/1034635
This way you can handle an arbitrary amount of numbers without duplicating logic everywhere.

php sum with add symbol as variable

I have this variable
$option_value['price'] = 2
$option_value['price_prefix'] = +
$this->data['price2'] = 3
I have tried to make sum from it like this
$price = $option_value['price'].''.$option_value['price_prefix'].''.$this->data['price2'];
echo $price
but the result is 2. What I want is 5.
Prease help
Under the assumption that the prefix is always either + or -, something like this should do the trick (I've changed the variable names for the sake of readability):
$price = 2;
$prefix = "+";
$price2 = 3;
$total = $price + ($prefix.$price2);
This concatenates the prefix and the second price to "+3" which will then be cast implicitly to an integer for the addition with the first price. The parentheses make sure that the concatenation is done before the addition. Otherwise the addition would precede and that would lead to concatenation rather than addition.
You can do this like this:
<?php
$option_value['price'] = 2;
$option_value['price_prefix'] = '+';
$option_value['price2'] = 3;
$price = $option_value['price']+$option_value['price_prefix']+$option_value['price2'];
echo $price;
?>

How to convert a string in a number PHP

I have a Foreach where I have two variables ($num1 and $num2) as string. I'd like to covert them as number (integer should be ok).
This is my code:
...
foreach ($titles as $match) {
list($num1, $num2) = explode(':', $results[$c++]->innertext); // <- explode
echo "<tr><td class='rtitle'>".
"<td class='last-cell'>".$match_dates[$c]->innertext . "</td> " .
//"<td class='first-cell tl'>".$match->innertext."</td> " .
" - ".$match->innertext." ".$num1.':'.$num2 . " " .
"<td class='odds'>".$best_bets[$b++]->attr['data-odd'] . ";" .
"".$odds[$b++]->attr['data-odd'] . ";" .
"".$odds[$b++]->attr['data-odd'] . "</td>" .
"</td></tr><br/>";
}
...
Thanks!
EDIT
Thanks for your answer. I am going to explain and maybe you could help me: I have a a problem with best_bets value, because it's not alway before odds variable, so I was thinking to use "if statement", where I can fix some rules: when $num1 is > $num2, I will show an echo order; when $num1 is = $num2 another echos order and. at least, $num1 is < $num2 another echos order. But to do this, I need to convert $num1 and $num2 to do it. I hope to be clear. Thank you for your helping
You could cast them to an int:
$num1 = (int) $num1;
Or use the intval function:
$num1 = intval($num1);
Hope this helps.

Echo statement not coming out as i want it [duplicate]

This question already has answers here:
Not getting the specific output without braces [closed]
(3 answers)
Closed 8 years ago.
This code only prints out '17' instead of "10 + 7 = 17". Why is this? And how can i solve this.
<?
$x = 10;
$y = 7;
echo $x . '+' . $y . '=' . $x+$y;
?>
What you should understand is that echo won't do anything until the result of the whole expression given to it is evaluated. This expression contains both . and + operators - the first one concatenates its operands (glues two strings together), the second adds numbers.
Now, you might think that + operator has a higher precedence than of . one - in other words, that result of $x + $y will be calculated before (eventually) glued to the rest of the string. But it's not. So we can say this statement is actually treated as...
echo ($x . '+' . $y . '=' . $x) + $y;
In other words, the result of all the string concatenation is added (converted to number) to $y, and only the result of this operation is printed.
The result of $x . '+' . $y . '=' . $x is '10+7=10', and it doesn't look like something that might be added. But guess what, PHP wants to be nice to you - and it assumes that you actually wanted to extract the first digits of a string when you tried to convert it to a number. So the whole line is treated as number 10. When added to 7, it's just 17 - that's why you got 17 echoed.
One possible workaround is getting rid of ., using , operator instead (as its precedence is lower - in fact, it's the lowest among operators):
echo $x, '+', $y, '=', $x + $y;
It could be simplified if one remember about such a handy feature of PHP as string interpolation:
echo "$x + $y = ", $x + $y;
<?php
$x = 10;
$y = 7;
function sum($a,$b){
return $a+$b;
}
echo $x.'+'.$y.'='.sum($x,$y);
?>

A very basic php query related to string concatenation and sum

<?php
$number1 = 1;
$number2 = 2;
echo $number1.' + ' . $number2. ' = '.$number1+$number2;
?>
See the above program. It is giving output as 3. Why not it is giving output as:
1 + 2 = 3
+ and . have the same precedence.
echo $number1.' + ' . $number2. ' = '.($number1+$number2);
The operations are applied in order. I.e:
echo $number1.' + ' . $number2. ' = '.$number1+$number2;
Becomes:
echo '1 + 2 = '.$number1+$number2;
Becomes:
echo '1 + 2 = 1'+$number2;
Since this is addition PHP will convert the string to an int which gives 1.
So the final expression is:
echo 1 + 2;//Prints 3
You can indicate which operations to perform together using brackets:
echo $number1.' + ' . $number2. ' = '.($number1+$number2);
your desired output :-
<?php
$number1 = 1;
$number2 = 2;
echo $number1.'+ ' . $number2.'='.($number1+$number2);
?>

Categories