If I were to have a string like the following:
$string = 1x2,3x5,6x6,;
Each section contains for example:
1 = amount, x2 = quantity.
Is there a way to split each segment between the commas up, then take the amount and times it by the quantity?
Thank you
Yes - by using explode
and list
(you can do it without list
, but it makes it easier with it):
$string = "1x2,3x5,6x6";
$total = 0;
$explode = explode(",", $string);
foreach ($explode as $explodeSegment) {
if (trim($explodeSegment) != "") {
list($amount, $quantity) = explode("x", $explodeSegment);
$total += ((int)$amount * (int)$quantity);
}
}
var_dump($total); //int(53)
You can use a function like this.
function evaluateExpressions($strings){
$expressions = explode(",", $strings);
$expressions = array_filter($expressions);
$matches = array();
$results = array();
foreach($expressions as $expression){
if (preg_match_all("/([0-9]+)([^0-9])([0-9]+)/", $expression, $matches)){
array_shift($matches);
print_r($matches);
$lh = array_shift($matches)[0];
$op = array_shift($matches)[0];
$rh = array_shift($matches)[0];
switch($op){
case "x":
$results[] = $lh * $rh;
break;
case "+":
$results[] = $lh + $rh;
break;
case "-":
$retults[] = $lh + $rh;
break;
case "/":
$results[] = $lh + $rh;
break;
default:
throw new Exception("I don't understand how to use ".$op);
}
} else {
throw new Exception("Malformed Expression List");
}
}
return $results;
}
If will evaluate a list of 2 term mathematical expressions and return an array of the results
Example Use:
$strings = "1x2,3x5,6x6,";
$dat = evaluateExpressions($strings);
print_r($dat);
would yield
Array
(
[0] => 2
[1] => 15
[2] => 36
)
As a bonus it also know how to use the other simple mathematical operators (+ - x /)