1

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

1
  • 1
    $result = $result * $element; maybe? Commented Feb 24, 2016 at 16:05

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yaaaas one lineerrr!!. Does array_filter use loose comparison for it's values? (ie "" == false instead of "" === false). I don't see a strict parameter like in_array has.
cannot find anything mentioned about comparison method used in array_filter. but you can always use the callback function where you can use strict comparison.
0
$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

Comments

0

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

Comments

0

You will need to use the integer value of the string as follows:

$product= 1;
foreach($parcalar as $element){
    $product = $product * intval($element);
}

intval Documentation

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.

1 Comment

Technically you don't need to.
0

To multiply all numbers:

$total = 1;

foreach($parcalar as $element){
    $total *= $element;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.