-1

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?

Furgas
  • 2,729
  • 1
  • 18
  • 27
fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • Sorry, corrected now – fightstarr20 Jan 31 '20 at 09:22
  • If you're looking for integers specifically then use [is_int](https://www.php.net/manual/en/function.is-int.php). is_numeric will allow a much wider variety of numbers (see the [docs](https://www.php.net/manual/en/function.is-numeric.php)). – ADyson Jan 31 '20 at 09:23
  • is_int looks good, but is there a way to attempt to cast it as an integer as well? – fightstarr20 Jan 31 '20 at 09:25
  • Why would you want to cast to integer as blank? You shouldn't blacklist values, as this renders your code outdated very quickly. Best to check if values ARE ints, and then run your code on that int if they are. Otherwise, don't run that code. – cmprogram Jan 31 '20 at 09:27
  • Did you google, for example "php cast to int"?? You'll get plenty of suggestions. https://stackoverflow.com/a/8529687/5947043 is useful info. You could read https://www.php.net/manual/en/language.types.type-juggling.php and https://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting as well. PHP is quite flexible abouts types - as long as it passes the is_int test you probably won't need to explicitly cast it most of the time. – ADyson Jan 31 '20 at 09:27
  • Casting `'test'` into an int would only get you `0`, not `NULL`. – 04FS Jan 31 '20 at 09:28

2 Answers2

1

You can do something like this:

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

function makeInteger($val){
    return is_numeric($val) ? (int)$val : null;
}

for($i=1;$i<=4;$i++){ 
    echo makeInteger(${"myVariable".$i}).PHP_EOL; 
}

Output:

2345
4433

1345

Demo

Note: casting (int) will remove float part of the variable.

Aksen P
  • 4,564
  • 3
  • 14
  • 27
1

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] =>
)
Loc Nguyen
  • 356
  • 3
  • 6