Home > database >  Using PHP what is the simplest way to check if multiple values are integers?
Using PHP what is the simplest way to check if multiple values are integers?

Time:12-02

I know one can likely use the switch statement but I have this currently to check that all function parameters that are supposed to be an int are and if not show an error:

if(!is_int($chartWidth)){
   echo "Chart width must be an integer";
}
if(!is_int($chartHeight)){
    echo "Chart height must be an integer";
}
if(!is_int($gridTop)){
    echo "Grid top must be an integer";
}
if(!is_int($gridLeft)){
    echo "Grid left must be an integer";
}

Can this be coded any more efficiently or shorter?

CodePudding user response:

if these are function parameters as you say, since PHP 5 you have been able to use type hinting for functions. Assuming you expect a value every time you can do the following.

function chart(int $width, int $height, int $top, int $left) {
    // Some code
}

If a value passed to the function is a type which is NOT an integer, you will get a fatal error.

CodePudding user response:

You could use a function:

function assertInt($value, $name)
{
    echo is_int($value) ? '' : $name . ' must be an integer.<br>';
}

assertInt($chartWidth,  'Chart width');
assertInt($chartHeight, 'Chart height');
assertInt($gridTop,     'Grid top');
assertInt($gridLeft,    'Grid left');

I don't like the echo inside the function, what if you have multiple variables that are not integers? I therefore added the <br> at the end.

CodePudding user response:

It is possible with dynamic variable names.

$chartWidth = 100;
$chartHeight = 200;
$gridTop = '1,2';
$gridLeft = 1.2;

$arr = [
  'chartWidth' => "Chart width must be an integer",
  'chartHeight' => "Chart width must be an integer",
  'gridTop' => 'Grid top must be an integer',
  'gridLeft' => 'Grid left must be an integer'
];

$result = [];
foreach($arr as $k => $v) {
    if(!is_int(${$k})){
        $result[] = $v;
    }
}

print_r($result);

output

Array
(
    [0] => Grid top must be an intege
    [1] => Grid left must be an integer
)

CodePudding user response:

This will iterate each variable and if you want to stop or print something before iterate the rest of variables i think it will be the best

 $data = array($chartWidth,$chartHeight,$gridTop,$gridLeft);
    
    foreach ($data as $value) {
        echo gettype($value) , "\n";
      if(gettype($value)!="integer"){
         // do something
       }
    }
  •  Tags:  
  • php
  • Related