首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对动态数组进行数学计算

对动态数组进行数学计算
EN

Stack Overflow用户
提问于 2016-03-22 04:04:09
回答 2查看 43关注 0票数 0

我有一个动态数组。

让我们假设

代码语言:javascript
复制
array (size=3)  
  0 => string '20' (length=2)  
  1 => string '-' (length=1)  
  2 => string '5' (length=1)

其结果将是20-5 =5

未定义数组大小,如何动态求解?

EN

回答 2

Stack Overflow用户

发布于 2016-03-22 04:25:01

您可以使用以下代码。当然,它也有一些局限性。这取决于你想做什么以及你为什么要这么做。

代码语言:javascript
复制
<?php

$array = array(
    '20',
    '-',
    '5',
    '*',
    '10'
);

$output = null;
$symbol = null;
foreach ($array as $item) {
    if ($item == '+' || $item == '-' || $item == '*' || $item == '/') {
        if ($output === null) {
            die("First item should be numeric! ");
        }
        $symbol = $item;
        continue;
    } elseif (!is_numeric($item)) {
        die("unknown symbol: " . $item);
    }

    // is numeric
    // first symbol

    if ($output == null) {
        $output = $item;
        continue;
    }

    if ($symbol === null) {
        die('Two numbers in a row!!');
    }

    switch ($symbol) {
        case '+':
            $output += $item;
            break;
        case '-':
            $output -= $item;
            break;
        case '*':
            $output *= $item;
            break;
        case '/':
            $output /= $item;
            break;

    }
}

echo "Calculation is: " . $output;
票数 2
EN

Stack Overflow用户

发布于 2016-03-22 04:35:11

phps最讨厌和最害怕的函数是为数不多的几个例子之一。

邪恶的eval()

代码语言:javascript
复制
$input = array('20', '-', '5');

// build formula from array by glueing values together
$formula = implode(' ', $input);

// execute the formula and store result in $result
eval('$result  = ' . $formula . ';');

// voila!
echo $formula . ' = ' . $result;

使用eval()的好处是,你可以使用所有已知的数学运算,甚至完全支持对括号的处理。

访问http://sandbox.onlinephpfunctions.com/code/71ffc94238a5510cd7b24632fc7a8b9b5cb2c2c0获取更多定义用于测试的公式的工作示例。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36140521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档