2

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?

3 Answers 3

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2
$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.

2 Comments

Simplest solution. Only issue is you won't know why it didn't work.
True. !$b may be either because the arrays were empty or because they were of different lengths. If you're really interested you can do a if (count($a) != count($csv)) to output the right error message.
1

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

1 Comment

True, but I think he's trying to prevent the warning from being thrown at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.