-2

I have an array like this:

Array
(
    [0] => firstname1,
    [1] => lastname1,
    [2] => firstname2,
    [3] => lastname2,
    [4] => firstname3,
    [5] => lastname3
)

Now I want to create a text file containing this content:

firstname1|lastname1#firstname2|lastname2#firstname3|lastname3#

How can I do that?

Progrock
  • 7,373
  • 1
  • 19
  • 25
stack
  • 10,280
  • 19
  • 65
  • 117
  • 3
    you can at least show us what you tried, if you did. – Funk Forty Niner Dec 16 '15 at 23:15
  • 2
    @Fred-ii- I just want to know, how can I create a `.txt` file using *PHP*. Just that, I will create a regex of my array later – stack Dec 16 '15 at 23:16
  • 1
    What relevance is the `#` ? And as mentioned by @Fred-ii- what have you tried so far? What didnt work? – Steve Dec 16 '15 at 23:17
  • 5
    http://php.net/manual/en/function.file-put-contents.php – Steve Dec 16 '15 at 23:18
  • You should check out `file_put_contents()` for file creation and insertion and `implode()` to convert the array into a string. http://php.net/manual/en/function.implode.php – BryanLavinParmenter Dec 16 '15 at 23:19
  • 5
    Google'd (for you) *"how to create a .txt file with php"* - http://stackoverflow.com/q/9265274/ and http://www.tizag.com/phpT/filecreate.php and http://www.tizag.com/phpT/filewrite.php and http://stackoverflow.com/q/14998961/ amongst many others. – Funk Forty Niner Dec 16 '15 at 23:19
  • Thanks everybody ... – stack Dec 16 '15 at 23:20
  • 3
    *hah!* someone even put in an answer using the links from above, *rich!* - Had I known, I'd of done the same ;-) but I'm not like that. – Funk Forty Niner Dec 16 '15 at 23:29

2 Answers2

1
$array = array(
    'firstname1',
    'lastname1',
    'firstname2',
    'lastname2',
    'firstname3',
    'lastname3'
);
$str = implode('@', $array) . '@';
$str = preg_replace('/(.+?)@(.+?)@/', '$1|$2#', $str);
file_put_contents('/tmp/file.txt', $str);

Edit inspired by: https://stackoverflow.com/a/16687155/3392762, and what came before.

Community
  • 1
  • 1
Juakali92
  • 1,155
  • 8
  • 20
1

You can iterate through the array in pairs, contcatenating with your chosen characters, to build a string, and then write it to a file with file_put_contents.

<?php
$names = array(
    'firstname1',
    'lastname1',
    'firstname2',
    'lastname2',
    'firstname3',
    'lastname3'
);

for(
    $i = 0, $n = count($names), $str = '';
    $i < $n;
    $i += 2
)
{
    $str .= $names[$i] . '|' . $names[$i+1] . '#';
}
file_put_contents('/tmp/names.txt', $str);

Or to build the string we could chunk the original array into pairs:

$str = '';
foreach(array_chunk($names, 2) as list($first, $second))
    $str .= $first . '|' . $second . '#';
Progrock
  • 7,373
  • 1
  • 19
  • 25