Anthony Miller
Anthony Miller

Reputation: 15919

PHP - use include() function within an array

How would I use the include() function within an array?

For example, I have an array which lists a bunch of counties, instead of inputting all of the counties into an array, I created a .txt file of comma delimited counties. Logically, I think it's supposed to work as such:

array (include ("counties.txt"));

But it produces the list outside of the array's function.

is there a different method of using the include() function within an array?

Upvotes: 0

Views: 4382

Answers (4)

nickjyc
nickjyc

Reputation: 128

One way is for your counties.txt file to have the following format:

<?php
return array(
    'country1',
    'country2',
    // etc.
);

Then, just include it in your array like:

<?php
$arr = include('counties.txt');

Another method is to parse counties.txt like:

<?php
$list = file_get_contents('counties.txt');

// Normalize the linebreaks first
$list = str_replace(array("\r\n", "\r"), "\n", $list);

// Put each line into its own element within the array
$arr = explode("\n", $list);

Either way works and will produce the same result.

Upvotes: 5

Patrick Moore
Patrick Moore

Reputation: 13344

I would try readfile(), separating each county on a new line. The readfile() function places each line of the file into an indexed array.

$array = readfile('counties.txt');

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191729

I think you just want to use file('countries.txt', FILE_IGNORE_NEW_LINES);

Upvotes: 3

Biotox
Biotox

Reputation: 1601

Try file_get_contents()

$temp_string = file_get_contents('counties.txt');
$temp_array = array($temp_string);

Upvotes: 2

Related Questions