0

I have a list in a text file:

 Alabama    
 Alaska     
 Alberta    
 ...

and I would like to have a PHP array like that :

 array('Alabama' => 'Alabama', 'Alaska' => 'Alaska', ...)

How could I have this array ? (I am a beginner in PHP and in computing in general). Thanks a lot

2
  • What exactly do you want to do, to have this array generated dynamically from a text file or is it a one-time task that you will save as PHP for later use? Commented Jul 2, 2012 at 21:25
  • 2
    identical key and value seems pointless. Commented Jul 2, 2012 at 21:28

3 Answers 3

2

You can use file() to read the entire file to an array, and use array_combine() to assign the array keys.

$arr = file('file.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$arr = array_combine($arr, $arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Very cool idea. Thank you @flowfree! I wish I could vote your post twice :-)
1
// read the file as an array of lines
$lines = file('./myFile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// fill the array
$arr = array();
foreach($lines as $line) {
    $arr[$line] = $line;
}

Comments

-1

You could actually read a file into an array.

$states=require('path/to/states.php');

then in the states.php file

return array(
   'Alabama' => 'Alabama',
   'Alaska' => 'Alaska'
   // and so on.
);

You would have to format your list, but that should be pretty easy using a text editor with regex.

1 Comment

Does your file contain an array?

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.