Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...