Reece Costello
Reece Costello

Reputation: 83

Write array values to file but with whitespace between each value

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.

Upvotes: 0

Views: 42

Answers (4)

Kitson88
Kitson88

Reputation: 2940

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 

Upvotes: 1

Pravin Vavadiya
Pravin Vavadiya

Reputation: 3207

Try to somthing like this...

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

Upvotes: 1

A.Mikhailov
A.Mikhailov

Reputation: 466

Try this:

$array = ['This', 'is', 'example'];    
$stringToWrite = implode(' ', $array);

Upvotes: 2

Jirka Hrazdil
Jirka Hrazdil

Reputation: 4021

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

Upvotes: 1

Related Questions