Search code examples
phparraysindexingoffsetundefined-index

PHP Array_combine undefined index


I want to combine two arrays, one as a key and the other as the data. However when I print_rthe array, I see that there was a mysterious space added to the keys. Even if I take a completely different array, the spaces seem to reappear after the array_combine.

Also if I try to access the array element by adding a space tot the key, I still get the error Undefined offset: 200.

This is my code:

$codes = file('H_codes.txt');
$sentences = file('H_sentences.txt');
$H_sentences_combined = array_combine($codes,$sentences);

echo $H_sentences_combined['200'];

I retrieve the arrays from two text files: H_codes.txt

200
201
202
...

and the $H_sentences file is in the same format (i.e. with no inline spaces, only next line spaces)

"Zeer licht ontvlambare aerosol."
"Ontvlambare aerosol."
"Zeer licht ontvlambare vloeistof en damp."
...

This is the result of the print_r($H_sentences_combined)

 Array ( [200 ] => "Instabiele ontplofbare stof." [201 ] => "Ontplofbare stof: gevaar voor massa-explosie." [202 ] => "Ontplofbare stof, ernstig gevaar voor scherfwerking." ...)

I really have no idea what's going wrong.

Any help is appreciated! Thank you.


Solution

  • That extra character is a newline character. file adds these to each line that it reads into an array.

    Change your file calls like so to get rid of those extra new line characters:

    $codes = file('H_codes.txt', FILE_IGNORE_NEW_LINES);
    $sentences = file('H_sentences.txt', FILE_IGNORE_NEW_LINES);
    $H_sentences_combined = array_combine($codes,$sentences);