Dirk van der Burgt Dirk van der Burgt - 6 months ago 12
PHP Question

PHP: Foreach loop causes the output to have an extra symbol that i don't want

Two different values are imported by html

<input>
tags. They should be displayed like this:
value1:value2
.
But they display like this instead:
value1:value2:
.
I know what is causing the problem but I don't know how to solve it because I'm just a beginner with PHP.

?php
$handle = fopen("text.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $value);
fwrite($handle, ":");
}

fclose($handle);
exit;
?

Answer

In every cycle inside the foreach you add a value and the colon. One option is to add the colon before the value is added and don't add it on the first run. Like this:

<?php

    $first = true;
    $handle = fopen("text.txt", "a");

    foreach($_POST as $variable => $value) {

        if(!$first) {
            fwrite($handle, ":");
            $first = false;
        }
        fwrite($handle, $value);

    fclose($handle);

?>

The implode solution from @xorifelse is also nice