简体   繁体   中英

PHP detecting correct variable type

I'm reading the contents of a text file into an array, and need to be sure which type of a specific entry is.

However my code sometimes is detecting empty values as integer and/or decimal. If the same script runs later for the same file, the type is detected right.

Any ideas?

<?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
    }
}
?>

For your situation, you are better off using if(){}elseif(){}else{} like this:

<?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
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM