Php 检查所有数字的均匀性

Php 检查所有数字的均匀性,php,Php,如何检查整数的所有数字是否为偶数 范例 $a = 22444648; $b = 324687; $a的所有数字都是偶数:2%2==0,4%2==0。。。所以我想回到现实。另一方面,$b应该返回false,因为3%2=0.您可以使用str\u split($integer)将整数拆分为一个数字数组。然后,您可以遍历数组元素,并在遇到非偶数的数字时立即返回false function isEven($integer){ $digits = str_split($integer);

如何检查整数的所有数字是否为偶数

范例

$a = 22444648;
$b = 324687;

$a
的所有数字都是偶数:2%2==0,4%2==0。。。所以我想回到现实。另一方面,
$b
应该返回false,因为3%2=0.

您可以使用
str\u split($integer)
将整数拆分为一个数字数组。然后,您可以遍历数组元素,并在遇到非偶数的数字时立即返回false

function isEven($integer){
    $digits = str_split($integer);

    foreach($digits as $digit){
        if($digit % 2 != 0) return false;
    }

    return true;
}

这个问题有很多可能的解决方案-如果您正在寻找一个线性,您可以使用检查整数是否包含所有偶数值

preg_match()如果模式与给定主题匹配,则返回1;如果不匹配,则返回0;如果发生错误,则返回FALSE

如果所有值均为偶数,则
/^[02468]+$/
的正则表达式应返回
1
,否则返回
0
(或
false
)。然后,它只是一个将结果转换为布尔值的例子;i、 e:

$a = 224455;
$hasAllEvens = (boolean) preg_match('/^[02468]+$/', $a);
我建议根据您的特定用例进行测试。例如,您必须支持负数吗?或者,是否可以接受填充数字;e、 g:
0024
甚至
00000

因为有很多可能的解决方案,你可以从其他选择中得到一些乐趣。这里有一个更复杂的例子:

<?php

// split the integer into an array and 
// apply a reduce function over each element.
// 
// this function applies a bitwise AND where 
// the left-hand value is 1, and the right-hand
// value is a single digit integer. an operation
// with an even number returns `0` and an operation
// with an odd number returns `1`. this result is 
// added to the `carry` value, which is the result
// of the previously applied function.
// 
// once iteration is complete, the resulting value
// is `0` is all integers were even, and a value
// greater than `0` representing a "count" of any
// odd values encountered.
//
// finally we negate this value to cast to 
// a boolean to get our final result.

function hasAllEvens($int)
{
    return !array_reduce(str_split($int), function ($carry, $item) {
        return (1 & $item) + $carry;
    });
}

// and a quick test... 
// any number that has at least one 
// odd integer will return false.

foreach (range(0, 21) as $int) {
    $result = hasAllEvens($int) ? 'yes' : 'no';
    printf("hasAllEvens(%d) -> %s\n", $int, $result);
}
等等


希望这有帮助:)

$array=str\u split($a);foreach($val作为数组){if($val%2==0){return true;}else{$return false;}}诸如此类。。。但它不起作用:(如果遇到偶数时立即返回true,则不起作用,否则将无法检查所有剩余的数字。我该如何做…?我已经编辑了我的答案。这是一个基本问题。此函数不会检查数组中的所有值,如果它们是偶数或非偶数…
$hasAllEvens=(布尔)preg\u匹配(“/^[02468]+$/”,$a);
?你试过什么吗?我喜欢
preg_match
方法:-)谢谢,这里也一样:)最短的解决方案通常是最好的!
hasAllEvens(0) -> yes
hasAllEvens(1) -> no
hasAllEvens(2) -> yes
hasAllEvens(3) -> no
hasAllEvens(4) -> yes
hasAllEvens(5) -> no
hasAllEvens(6) -> yes
hasAllEvens(7) -> no
hasAllEvens(8) -> yes
hasAllEvens(9) -> no
hasAllEvens(10) -> no
hasAllEvens(11) -> no
hasAllEvens(12) -> no
hasAllEvens(13) -> no
hasAllEvens(14) -> no
hasAllEvens(15) -> no
hasAllEvens(16) -> no
hasAllEvens(17) -> no
hasAllEvens(18) -> no
hasAllEvens(19) -> no
hasAllEvens(20) -> yes
hasAllEvens(21) -> no