phpfileimplode

Creating a string from a Php array and writing it to a text file


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?


Solution

  • 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 . '#';