2

I want to write an array to a file, but instead of looking like this:

array (
  0 => 'Something 1
',
  1 => 'Something 2
',
  2 => 'Something 3
'
)

It should look like this:

Something 1
Something 2
Something 3

Is it possible? I'm currently using this method to write an array to a file:

file_put_contents('array.txt', var_export($array, TRUE));
7
  • is this your homework? Commented Nov 11, 2016 at 14:37
  • 1
    Nope. Why would you ask? Commented Nov 11, 2016 at 14:38
  • Many ways, loop over the array and write row-by-row, join all values and write it all at once, etc. Commented Nov 11, 2016 at 14:41
  • 1
    file_put_contents($path, $array) Commented Nov 11, 2016 at 14:43
  • Normally it's usually homeworks that requires text files or assignments from school Commented Nov 11, 2016 at 14:44

3 Answers 3

6

A very simple method:

file_put_contents('array.txt', implode(PHP_EOL, $array_data));
Sign up to request clarification or add additional context in comments.

1 Comment

all answers are correct so far but this is the most eloquent answer.
1

var_export() would simply turn the Array to its String Representation/Equivalent just like What you have up there [The Exact same Array Structure but just as a String DataType]. You may have to simply build the String Output using a Loop and then save the Resulting String. That way, you get the kind of Result you expected. The Snippet below attempts to capture the idea here:

    $arr                = array (
        0 => 'Something 1',
        1 => 'Something 2',
        2 => 'Something 3'
    );

    $writableStr        = "";

    foreach($arr as $value){
        $writableStr   .= $value . "\n";
    }

    file_put_contents("array_data.txt", $writableStr);

Comments

1

You can loop through the array and write the contents in a string

 foreach ($array as $item){
    $str .= $item . '\n';
 }

 file_put_contents('array.txt', $str);

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.