Jump to content

Text file to an array


rbrown

Recommended Posts

I'm trying to open a file which is saved as the first line is the key the second line is the value and so on...

 

When I loop through it I keep getting the keys and values screwed up.

 

It either returns the key and the value and then the value is the next key

Or

it returns each key and value as a value.

 

Thanks,

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/93821-text-file-to-an-array/
Share on other sites

<pre>
<?php
$contents = array_chunk(file("data.txt"),2);

$final = array();
foreach ($contents as $array) {
    
    $final[rtrim($array[0])] = $array[1];
    
}

print_r($final);

//or

$contents  = file("data.txt");
$size      = count($contents);
$final     = array();

for ($i=0;$i<$size;$i++) {

    $final[rtrim($contents[$i])] = $contents[++$i];

}

print_r($final);
?>

Link to comment
https://forums.phpfreaks.com/topic/93821-text-file-to-an-array/#findComment-480760
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.