user1793646
user1793646

Reputation: 35

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.

Upvotes: 0

Views: 825

Answers (2)

Nathan
Nathan

Reputation: 331

The character after the index is not actually a space, it's a newline (or two). Basically in your text file at the end of each line will be either \n or \r\n. To remove these before inserting, simply use the trim($content) function built into PHP, which will remove all whitespace at the left and right of the string. e.g. trim(' hello world! ') would return 'hello world!'

Upvotes: 0

Buggabill
Buggabill

Reputation: 13901

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);

Upvotes: 2

Related Questions