douhao7677
douhao7677
2018-04-02 22:03
浏览 65
已采纳

从php中的数组中获取对称整数的总数?

ok so i have array for example $arr= "/43sdsd555ksldk66sd"544fdfd";

I take numbers using preg_match_all '/\d+/', and array_map('intval', $zni[0]);

Now the problem is i need to reverse those whole int to see if they are symmetric,like 555 and 66 , and if they are GET A TOTAL OF THEM.(total of only symmetric numbers)

i tried to use function " strrev "and got symmetric numbers, but i don't know how to put them in a one place IF THEY ARE symmetric and calculate them.

<?php
$numbers = "";

if (isset($_GET['submit']))
{
    $numbers = ($_GET['niz']);
    preg_match_all('/\d+/', $numbers, $zni);
    $numtwo= array_map('intval', $zni[0]);
}

foreach ($numtwo as $num)
{
    $reverse = strrev($num);
    var_dump($reverse);

    if ($num == $reverse)
    {
        $reverse = "true";
    } else {
        $reverse = "false";
    }
    var_dump($reverse);
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douling8087
    douling8087 2018-04-02 22:44
    已采纳

    Since you already got most of the way there and all you were missing basically was to use + or +=, here is an easy example on how to do it:

    $input = "/43sdsd555ksldk66sd544fdfd";
    $total = 0;
    
    preg_match_all('/\d+/', $input, $m);
    foreach ($m[0] as $d)
        if ($d == strrev($d))
            $total += $d;
    
    var_dump($total); // => int(621)
    

    Using intval() is not necessary as PHP will implicitly cast between types as needed.

    Alternatively you can replace the loop with PHP's array_* functions:

    $input = "/43sdsd555ksldk66sd544fdfd";
    
    preg_match_all('/\d+/', $input, $m);
    $total = array_sum(array_filter($m[0], function ($v) { return $v == strrev($v); }));
    
    var_dump($total); // => int(621)
    

    Here we use an anonymous function with array_filter() to generate a new array that only contains palindrome numbers from the original matches which is then given to array_sum().

    So all that's needed to transform your original code into a working example, is introducing a variable and summing up:

    <?php
    $numbers = "";
    
    if (isset($_GET['submit']))
    {
        $numbers = ($_GET['niz']);
        preg_match_all('/\d+/', $numbers, $zni);
        $numtwo= array_map('intval', $zni[0]);
    }
    
    $total = 0; // new variable
    foreach ($numtwo as $num)
    {
        $reverse = strrev($num);
        var_dump($reverse);
    
        if ($num == $reverse)
        {
            $reverse = "true";
            $total += $num; // sum up
        } else {
            $reverse = "false";
        }
        var_dump($reverse);
    }
    
    var_dump($total); // => int(621)
    
    点赞 评论

相关推荐