Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a date using filter_var_array

Tags:

php

I have a csv file that contains lines with a format as follows:

Name;timestamp;floatValue

The file has over than 20000 lines, and I want to filter each value of each line. I tried using this code :

$args=array(FILTER_SANITIZE_STRING,FILTER_VALIDATE_INT,FILTER_VALIDATE_FLOAT);
while (($line = fgetcsv($handle, 1024, ";")) !== FALSE) {

        $testing = filter_var_array($line,$args);
        var_dump($testing);
}

I get this error:

 filter_var_array(): Numeric keys are not allowed in the definition array

So I have 2 problems here:

  • Why do I get this error ? In fact, as I can't get from the line an array with keys and values, I don't know how to still use the filter_var_array
  • How to combine filtering strings, floats with a date ? is it possible to skip the date in the middle to filter it after separetly by using DateTime::CreateFromFormat ? I checked this doc but there is no filter for dates.

:::EDIT:::

What about this:

  $data = array(
        'name' => $line[0],
        'timestamp' => $line[1],
        'value' => $line[2]);

        $args=array(
          'name' => FILTER_SANITIZE_STRING,
          'timestamp' => FILTER_VALIDATE_INT,
          'value' => FILTER_VALIDATE_FLOAT);
        $testing = filter_var_array($data,$args);
        var_dump($testing);

Kindly tell me if it's a good approche.

like image 383
JavaQueen Avatar asked Jul 06 '26 11:07

JavaQueen


1 Answers

filter_var_array works with associative arrays, not numeric,

you have to transform your arrays by adding associative keys

$args = array('string' => FILTER_SANITIZE_STRING, 'int' => FILTER_VALIDATE_INT, 'float' => FILTER_VALIDATE_FLOAT);
$keys = array('string', 'int', 'float'); 
while (($line = fgetcsv($handle, 1024, ";")) !== FALSE) {
    $testing = filter_var_array(array_combine($keys, $line), $args);
    var_dump($testing);
}
like image 127
beta-developper Avatar answered Jul 09 '26 02:07

beta-developper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!