1

I am pretty new to PHP and am trying to use variables in a string, here is my code:

<?php
    $userName = $_GET['Username'];
    $message = $_GET['Message'];

    if($_POST['Submit']){ 
        $open = fopen("new.txt",'a'); 
        $text = "\n________________________________________"+$userName+":"+$message+"\n________________________________________";
        fwrite($open, $text); 
        fclose($open); 
        echo "File updated.<br />";  
        echo "File:<br />"; 
        $file = file("new.txt"); 
        foreach($file as $text) { 
            echo $text."<br />"; 
        }
    }
?>

Also, would I use 'a' for adding to a file? If not what would I use? Please help me, thanks in advance!

4 Answers 4

3

Use . instead of + for concatenation.

Or, you can just do:

$text = "\n________________________________________$userName:$message\n________________________________________";

or (to be slightly clearer to the parser):

$text = "\n________________________________________{$userName}:{$message}\n________________________________________";
3
  • 2
    Personally, I don't like variables put into strings and I always recommend using the explicit syntax of "____" . $var . "____" as things like code highlighting work...
    – Dan Soap
    Jun 16, 2011 at 21:01
  • Sometimes it looks a lot nicer to put them in the string. Matter of preference.
    – ceejayoz
    Jun 16, 2011 at 21:06
  • 1
    @cassy: with a PHP-aware syntax highlighting editor, variables inside strings stick out like a sore thumb. Personally I prefer embedding to having to wasting visual space with uncessary quotes/concatenation operators.
    – Marc B
    Jun 16, 2011 at 21:23
2

I always like single quotes (when possible) cause they are faster:

$str = '5+5='.(5+5);

Also comma for echo instead of concatenation cause is faster:

echo '5+5=',(5+5);

And in very complex strings (if don't care for speed) and also quotes needed I use variables to make things look more clear:

 $dbq="\"";
 $sq='\'';
 echo $dbq,'This is in double quotes.',$dbq,'<br>';
 echo $sq,'This is in single quotes.',$sq;
1

$text = "\n___$userName:$message\n" will work. Also $text = "whatever{$var}bar{$var2}". The documentation for fopen is available here and says of 'a':

Open for writing only; place the file pointer at the end of the file.

'a' in this context generally means 'append'.

1
0
$text = "\n________________________________________".$userName.":".$message."\n________________________________________";

Use . for concatination

a would append to a file, so u want to replace the content you would use w

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.