Reputation: 1297
I am reading in certain values of a CSV file into an array, and I want to run some basic validation checks against each value before inserting each row into a MySQL database. I'm wondering how to do this efficiently, with some sort of rules array.
e.g i only want values at certain positions in each row of the CSV
$while ($data = fgetcsv....)
$val1 = $data[2];
$val2 = $data[9];
$val3 = $data[11];
I want to validate each val - if any of the vals doesn't validate, will abort insert
if (ctype_alnum($val1) AND ctype_alnum($val2) AND is_numeric($val3))
The above approach starts to look pretty inefficient when dealing with approx 30 values, so I was wondering if a way to improve it by creating an array which stores the desired value position and also the validation rule. Something like the below...
$vals = array(
'val1' => array('pos' => 2, 'rule' => 'ctype_alphanum')
)
Any pointers on this would be great..!
Upvotes: 2
Views: 550
Reputation: 4389
I have no idea what for you need pos
element in array, but for the other part you can look into this. If more complex needed change it accordingly
$vals = array(
'val1' => array(
'rule' => 'ctype_alnum',
),
'val2' => array(
'rule' => 'ctype_digit',
),
);
function print_out( $val )
{
echo '<pre>';
var_dump( $val );
echo '</pre>';
}
print_out( $vals );
array_walk( $vals, function( &$value, $key ){
$result = call_user_func( $value['rule'], $value['value'] );
$value['result'] = $result;
});
print_out( $vals );
UPDATE
$var = fgetcsv(...);
here you get a row from csv.
$neededRange = array_slice( $var, $x[, $n] );
this way you will get the part you need.
And since I see you only need one rule for all elements, then.
array_walk( $array, function( &$value, $key ){
$value = array(
'value' => $value,
'rule' => 'ctype_alnum',
);
});
Also updated validation algorithm.
Upvotes: 1