-1

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?

8

2 Answers 2

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 . '#';
Sign up to request clarification or add additional context in comments.

Comments

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.

9 Comments

This is about the only answer (so far) that makes any sense.
it isn't actually right as i didn't read the output correctly which is my fault. I'll edit it shortly
No problemo. I wasn't criticizing it, do what you can ;-)
@Fred-ii- I have a question of You, you know the answer ... is it not? So why you don't write an answer under my question? really why?
@stack so I'm the one who gets "shot at", sigh. Double rich.
|

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.