PHP检测正确的变量类型

时间:2018-03-07 15:00:03

标签: php variables types

我正在将文本文件的内容读入数组,并且需要确定特定条目的类型。

但是我的代码有时会将空值检测为整数和/或小数。如果同一脚本稍后运行同一文件, 检测到的类型是正确的。

有什么想法吗?

<?php
$file = fopen($file, "r");
$row = 0;

while ($fscv = fgetcsv($file, 0, ';')) {
    if ($row == 0) {
        $header = $fscv;
    } elseif ($row == 1) {
        $values = $fscv;
    }
        $row++;
}
fclose($file);

foreach ($values as $value) {
    switch (true) {
        case $value == NULL:
            $value = '';
            // do something
            break;
        case $value == '':
            $value = '';
            // do something
            break;
        case $this->validateDate($value):
            // do something
            break;
        case is_int($value):
            // do something
            break;
        case is_numeric($value):
            // do something
            break;
        default:
            // do something
    }
}
?>

1 个答案:

答案 0 :(得分:0)

根据您的情况,您最好使用if(){}elseif(){}else{}这样:

<?php
$file = fopen($file, "r");
$row = 0;

while ($fscv = fgetcsv($file, 0, ';')) {
    if ($row == 0) {
        $header = $fscv;
    } elseif ($row == 1) {
        $values = $fscv;
    }
    $row++;
}
fclose($file);

foreach ($values as $value) {
    if( $value === '' ) {
        // the string is empty
    }
    elseif(ctype_digit($value)) {
        // we have an integer
    }
    elseif(strtolower($value) === 'true') {
        // boolean true?
    }
    elseif(strtolower($value) === 'false') {
        // boolean false?
    }
    elseif(
        substr_count($value, '.') === 1 && // single period
        strpos($value, '.') !== (strlen($value)-1) && // period cannot be the last character
        preg_replace('/[0-9]/', '', $value) === '.' // remove all digits and make sure that only a period is left
    ) {
        // float?
    }
    elseif($this->validateDate($value)) {
        // date?
    }
    else{
        // idk, do something
    }
}
?>