0

I need to write an array to a .csv file in PHP.

Example array:

$array = array(
    "name" => "John",
    "surname" => "Doe",
    "email" => "[email protected]"
);

By using implode(",", $array), I get a result like this:
John,Doe,[email protected]

However, I need to also write the key of each element to the file.

The desired output is this:
name:John,surname:Doe,email:[email protected]

How would I achieve this?

1

5 Answers 5

11

Try this code:

$out = $sep = '';
foreach( $array as $key => $value ) {
    $out .= $sep . $key . ':' . $value;
    $sep = ',';
}
Sign up to request clarification or add additional context in comments.

1 Comment

I really like your solution with $sep for avoiding the classic problem of the trailing comma after the final key-value pair.
1
$csv = "";

foreach($array as $key => $data)
{
    // be sure to add " in your csv
    $csv .= '"'.$key.':'.$data.'",';
}

// and add a new line at the end
$csv .= "\n";

echo $csv;

1 Comment

This will add a newline after every key-value pair, which is not what Jack is asking for. Also, this will leave a trailing comma after the final key-value pair.
0

The answers above outputs a trailing comma at the end. To correct this, I use the following function:

$array = array(
    "name" => "John",
    "surname" => "Doe",
    "email" => "[email protected]"
);
function implodeKV($glueKV, $gluePair, $KVarray){
    $t = array();
    foreach($KVarray as $key=>$val) {
        $t[] = $key . $glueKV . $val;
    }
    return implode($gluePair, $t);
}

echo implodeKV( ':' , ',' , $array);
// outputs  name:John,surname:Doe,email:[email protected]

http://phpassist.com/2dde2#2

Comments

0

If you're using PHP 5.3+, then an anonymous function can make your code a lot cleaner, though a simple for loop has the best performance. (Using array_walk comes close though!)

I ran some tests with a few different approaches (using PHP 5.4.33):

function makeArray(&$a) {
    $a = array();
    for($i = 0; $i < 100000; $i++) {
        $a[rand()] = rand();
    }
    return $a;
}

makeArray($array);
$before = microtime(true);
$result = implode(
    ",", 
    array_map(
        function($k, $v) {
            return "$k:$v";
        }, 
        array_keys($array), 
        $array
    )
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ anonymous function: {$dur}s<br>";

makeArray($array);
$before = microtime(true);
function kv_func($k, $v) {
    return "$k:$v";
}
$result = implode(
    ",", 
    array_map(
        "kv_func", 
        array_keys($array), 
        $array
    )
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ function: {$dur}s<br>";

makeArray($array);
$before = microtime(true);
array_walk(
    $array,
    function(&$v, $k) {
        $v = "$k:$v";
    }
);
$result = implode(
    ",", 
    $array
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Walk w/ anonymous function: {$dur}s<br>";

makeArray($array);
$before = microtime(true);
$ff = true;
$sep = ",";
$out = "";
foreach($array as $key => $val) {
    if($ff) $ff = false;
    else $out .= $sep;
    $out .= "$key:$val";
}
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop w/ loop flag: {$dur}s<br>";

makeArray($array);
$before = microtime(true);
$out = "";
foreach($array as $key => $val) {
    $out .= "$key:$val,";
}
$out = substr($out, 0, -1);
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop + substr: {$dur}s<br>";

Results:

Array Map w/ anonymous function: 0.13117909431458s
Array Map w/ function: 0.13743591308594s // slower than anonymous
Array Walk w/ anonymous function: 0.065797805786133s // close second
Foreach loop w/ loop flag: 0.042901992797852s // fastest
Foreach loop + substr: 0.043946027755737s // comparable to the above

And just for kicks, I tried the for loop without correcting for the trailing comma. It didn't really have any impact:

Foreach loop w/ trailing comma: 0.044748067855835s

Comments

-1
<?php
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "[email protected]"
);
foreach( $array as $key=>$data ) {
$output .= $comma . $key . ':' . $data;
$comma = ',';
}

echo $output;

?>

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.