'PHP - Variable Inside Quotes or Outside?
I'm just coming back to PHP. I wanted to know which coding practice is preferred and why one may be better or worse than the other?
<?php
$x = 10;
echo "Variable x is: $x";
// OR This version
echo "Variable x is: " . $x;
?>
The top echo is new to me because I've always done it as the second method.
Solution 1:[1]
By default, PHP automatically scans all strings delimited by " as one that contains a variable, then substitutes the variable, so concatenating onto the end makes no sense. However, if you were using a single quote, ' , then you would need to use a concatenated operator. My general rule of thumb is that if you aren't concatenating, don't bother with ", as you're wasting cycles. Therefore, your first example is the "correct" one, but only in the sense that it uses " as it was meant to be used.
Solution 2:[2]
I would recommend the first method as it is more readable to other programmers who are working on the code because it is the conventional way of echoing
Solution 3:[3]
Both of them are correct. and IMO its up to coder's preferences...
echo "Variable x is: {$x}"; // notice use of {} is better then:
echo "Variable x is: $x";
echo "Variable x is: ".$x; // is also fine
printf("Variable x is: %s", $x); // another neat way is to use
sprintf()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zarathuztra |
| Solution 2 | Computernerd |
| Solution 3 | arkascha |
