0

I want to write my array values to a file which i can do but the output ends up looking something like this:

Thisisanexample

I basically want to split every array value up to look like this:

This is an example

The array is what you would expect:

Array
(
[0] => This
[1] => is
[2] => an
[3] => example
)

I'm not sure how I could formulate this.

4
  • And how are you writing it to your file, exactly? Commented Nov 28, 2016 at 12:13
  • Please provide your code here... Commented Nov 28, 2016 at 12:14
  • if all you do is flat out concatenate the array values then that is exactly the result you will get. you would need to do something like array[0] + " " + array[1] + " " + array[2]..... Commented Nov 28, 2016 at 12:15
  • You can use implode() to get the string you want. Commented Nov 28, 2016 at 12:17

4 Answers 4

2

Try this:

$array = ['This', 'is', 'example'];    
$stringToWrite = implode(' ', $array);
Sign up to request clarification or add additional context in comments.

1 Comment

Works, Thank you.
1

If your data is small, you can use implode().

fwrite($fp, implode(' ', $data));

Otherwise you would use a foreach and a little fiddling:

$lastValue = array_pop($data);
foreach ($data as $d) {
  fwrite($fp, $d);
  fwrite($fp, ' '); # or any other separator
}
fwrite($fp, ' ');
fwrite($fp, $lastValue);

Comments

1

Try to somthing like this...

  $write = array(
     '0' => 'This',
     '1' => 'is',
     '2' => 'an',
     '3' => 'example'
   );
   $stringToWrite = implode(' ', $write);
   fwrite($file, $stringToWrite);

1 Comment

Thank you, if only i could select multiple answers
1

You could also use a foreach() loop and then concatenate the value with whitespace.

$array = ['This', 'is', 'an', 'example'];

foreach ($array as $v) {

    echo $v . " ";

}

Output

This is an example 

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.