0

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

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
Faiz
  • 117
  • 1
  • 10

2 Answers2

0

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.

simon
  • 2,896
  • 1
  • 17
  • 22
0

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; 

?>
Xenolion
  • 12,035
  • 7
  • 33
  • 48
Mohit Kumar
  • 952
  • 2
  • 7
  • 18
  • it don't work. When I change $option_value['price_prefix'] = '-'; the result still the same – Faiz Feb 28 '18 at 22:26