0

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?

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As per php.net/manual/en/function.include.php (example #5) on PHP.net, include() does not return the contents of the file; it simply returns 1 unless there is a return statement within the file. In that case, it will return the contents of the return; statement. So it wouldn't work with non-.php files anyway. I recommend instead using readfile() or filegetcontents() as is explained in the other answers.
Fixed. Thanks for noticing that.
3

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

1 Comment

oddly enough file() is what did the trick for my problem. Thanks.
2

Try file_get_contents()

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

Comments

2

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

Comments

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.