Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

php - How do i multiply values of an array

I get this error message "array_product() expects parameter 1 to be array, string given in..." when i try to multiply all the values in the foreach statement below. Kindly help. Thanks in advance

Here is my code. Note that the values in $answer is usually something like "1.50 real(Yes)". but i only need the "1.50" as many as they are in the loop to multiply and get total.

foreach($_POST['gm'] as $key => $answer){
    if($answer != ''){
    $odd=explode(" ",$answer);
    $od=trim($odd[0]);
}
$total = array_product($od);
echo $total;

I try to do the multiplication outside the loop as above with $total. so as not to repeat in the loop. Any help with this please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not reconstructing an array in your foreach loop. So your $od variable does just get overridden each time you loop.

Your code should be

foreach($_POST['gm'] as $key => $answer) {
    if($answer != '') {
        $odd = explode(" ",$answer);
        $od[] = trim($odd[0]);
    }
}
$total = array_product($od);
echo $total;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...