Example There is a variable (123.4234.1.3.) I need explode this (.) And multiply 123 4234 1 3
$formatted="123.4234.1.3.";
$parcalar = explode(".", $formatted);
foreach($parcalar as $element),
how can i continue
$formatted="123.4234.1.3.";
$numbers = explode(".", $formatted);
$mul = array_reduce($numbers, function ($carry, $value) {
if ($value === "") { // skip empty values
return $carry;
}
return $carry * $value;
}, 1);
var_dump($mul);
Output:
int(1562346)
array_reduce
anyone? :D
To multiply all numbers:
$total = 1;
foreach($parcalar as $element){
$total *= $element;
}
You will need to use the integer value of the string as follows:
$product= 1;
foreach($parcalar as $element){
$product = $product * intval($element);
}
Besides for a string as yours ("12.4.1.3."
) which contains a dot at the end, the explode function would return an array as:
Array ( [0] => 12 [1] => 4 [2] => 1 [3] => 3 [4] => )
The last value becomes 0. So make sure the string doesn't end in a dot(.) unless that is what you want.
Here's the caveman solution in case anyone is interested
$var = "123.12.2";
$tempstring = " ";
$count = 0;
$total = 1;
$length = strlen($var);
for($i=0;$i<=$length;$i++)
{
if($var[$i]!='.' && $i!=$length)
{
$tempstring[$count] = $var[$i];
$count++;
}
else//number ended, multiply and reset positions, clear temporary char array
{
$total *= intval($tempstring);
$count=0;
$tempstring = " ";
}
}
echo $total;
will output 2952
One liner!
Explode, remove blank items with array_filter and use array_product
$product = array_product(array_filter(explode(".", $formatted)));
Reference: array_product
If need strict filter you can use the callback with strict comparison.
$product = array_product(array_filter(explode(".", $formatted),
function ($v){ return (int)$v !== 0; }));
Here is a Demo