-4

In PHP how do you know if you should use each form of echo, and what is the proper uses for each:

with the period:

 echo"<div>
        <img src='".$row['image']."'>
        ".$row['text']."
    </div>

with the comma:

echo"<div>
    <img src='",$row['image'],"'>
    ",$row['text'],"
</div>

with the {}:

echo"<div>
    <img src='{$row['image']}'>
    {$row['text']}
</div>

preset:

$image=$row['image'];
$text=$row['text'];
    echo"<div>
        <img src='$image'>
        $text
    </div>

More specifically I'm looking for the difference in how PHP will add the text to the HTML dump on the front end.

i am me
  • 91
  • 1
  • 14
  • nope, it's about how to use each one properly, because when using the . I've noticed that php will sometimes put the stuff at the end of the page, but with the , it sometimes won't. – i am me Oct 02 '15 at 19:53
  • But if you understand the differences then you know how to use them. – takendarkk Oct 02 '15 at 19:59
  • 1
    "sometimes put the stuff at the end of the page" - No, it doesn't. That only happens when mashing in user functions that print stuff out of expression context. – mario Oct 02 '15 at 20:03
  • Don't things like while loops, and stuff do that on dumps? – i am me Oct 02 '15 at 20:17

3 Answers3

3

. concatenates strings (+ in most languages, but not PHP). PHP manual operators

, separates arguments (echo can take more than 1 argument). PHP manual echo

x13
  • 1,985
  • 1
  • 8
  • 27
1

In your first example echo" ".$row['text']." must be changed to echo " ".$row['text']." which is write syntax to concatenate two string. For second example echo" ",$row['text']," must be changed to echo " ",$row['text']," I don think this is valid syntax in php . $image=$row['image']; $text=$row['text']; echo" $text must be like

$image=$row['image']; $text=$row['text']; echo $text;

Exception
  • 731
  • 3
  • 16
0

with period:

echo"<div>
        <img src='".$row['image']."'>
        ".$row['text']."
    </div>";

src='".$row['image']."' denotes the concatenation of $row['image']

with comma:

echo"<div>
    <img src='",$row['image'],"'>
    ",$row['text'],"
</div>";

^The comma , defines the string separation in the above example.

preset:

$image=$row['image'];
$text=$row['text'];
    echo"<div>
        <img src='$image'>
        $text
    </div>

^While this would still work with single '$image' A better practice would be '".$row['image']."' wrapped around quotes, i.e. below:

echo "<div>
    <img src='".$image."'>
    ".$text."
</div>";

Note: Keeping it simple, . for concatenation and , for separation.

^An Example:

<?php
$str = "Hawas" . "Ka" . "Pujaari";

echo $str;

$str2 = "Hawas, " . "Ka, " . "Pujaari";

echo  $str2;
?>
DirtyBit
  • 15,671
  • 4
  • 26
  • 53