温馨提示:本文翻译自stackoverflow.com,查看原文请点击:php - Cast variable to integer or null if not able to
php

php - 如果无法将变量转换为整数或null

发布于 2020-03-27 16:18:56

在PHP中,我有3个这样的变量集...

$myVariable1  = '2345';
$myVariable2  = 4433;
$myVariable3  = 'test';

我想确保它们都是整数,如果不是,那么我想将它们设置为空白。我已经阅读过is_numeric,但是不确定这是否是正确的函数。

if (!is_numeric($myVariable1)) {
    $myVariable1 = 2345;
}

if (is_numeric($myVariable2)) {
    $myVariable2 = 4433;
}

if (!is_numeric($myVariable3)) {
    $myVariable3 = NULL;
}

有没有一种方法可以自动执行此操作,因此它将尝试转换为整数或在无法设置时设置为NULL?

查看更多

查看更多

提问者
fightstarr20
被浏览
16
Loc Nguyen 2020-01-31 17:32

尝试这个

$a = '1234';
$b = '3333';
$c = 'test';

list($a1, $b1, $c1) = array_map(function($elem) { return is_numeric($elem) ? intval($elem) : null; }, [$a, $b, $c]);

结果

print_r([$a1, $b1, $c1]);
Array
(
    [0] => 1234
    [1] => 3333
    [2] =>
)