Warm tip: This article is reproduced from stackoverflow.com, please click
php

Cast variable to integer or null if not able to

发布于 2020-03-27 15:47:16

In PHP I have 3 variables set like this...

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

I am trying to ensure that these are all integers and if not then I would like to set them as blank. I have read up on is_numeric but am not sure if this is the correct function to use.

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

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

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

Is there a way to do this automatically so it will attempt to cast to an integer or set NULL if not able to?

Questioner
fightstarr20
Viewed
21
Loc Nguyen 2020-01-31 17:32

Try this

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

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

Result

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