开发者

Catch array combine warning and print own error message?

开发者 https://www.devze.com 2023-03-06 04:39 出处:网络
I read some csv file and map the contents to the field names using array_combine: $csv = array(); $a = array(\'some fields\');

I read some csv file and map the contents to the field names using array_combine:

$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine() [function.array-combine]: Both parameters should have an equal number of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the 开发者_开发技巧warning?


Grab the number of columns in the CSV and then compare it to $a's length. Since you didn't specify, I'll assume the array is one dimensional with each line from the CSV file.

if (count($csv) > 0 && count($a) == count(explode(',', $csv[0]))) {
    // Valid
} else {
    // Not valid
}


$b = @array_combine($a, $csv);
if (!$b) {
    // error!
}

You should not (ab)use the @ operator, but in this case it does most literally what you want.


According to the docs if either array is empty or if they are of different lengths, array_combine will return false.

So you should be able to do something like:

if($b = array_combine($a, $csv)) {

} else {
   ... the warning occurred ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消