开发者

HTML & PHP : Doublequotes-Singlequotes Issue [duplicate]

开发者 https://www.devze.com 2023-01-11 16:39 出处:网络
This question already has answers here: 开发者_开发百科 What is the difference between single-quoted and double-quoted strings in PHP?
This question already has answers here: 开发者_开发百科 What is the difference between single-quoted and double-quoted strings in PHP? (7 answers) Closed 8 years ago.

in HTML

we can

face='Tahoma'
face="Tahoma"

and in PHP

$name = "Junaid";
$name = 'Junaid';
$names = array('Junaid','Junaid','Junaid');
$names = array("Junaid","Junaid","Junaid");

now all these statements are correct with single or double quotes but

  • what difference does it make
  • which is the preferred method
  • what types of quotes to use where

which one of the following is correct

$link = "www.anyLINK.com"

echo "<a href=' ". $link ." '>Click Here</a>"

echo "<a href= ". $link ." >Click Here</a>"


The difference between single and double quotes in PHP is that PHP will read variables inside of double quotes but not single. For example:

<?php
$variable = "test";

echo "Can you see this $variable"; // Can you see this test
echo 'Can you see this $variable'; // Can you see this $variable

?>

The single quote will be read literal, where was double will attempt to replace the $variable with it's value.

Optimization Differences
As pointed out in the comments below, single quotes tend to be faster than double. In a quick benchmark, double quotes with any $'s escaped is the fastest vs single and double with and without $variables in the string. See http://codexon.codepad.org/54L3miwN


See http://php.net/manual/en/language.types.string.php.

In particular, variables are expanded in double quotes:

$foo = 42;
print('foo is $foo'); // foo is $foo
print("foo is $foo"); // foo is 42


In HTML, it doesn't matter at all.

In PHP, it does. Using the single-quotes prevents variables from being interpreted; for instance, echo '$foo'; will print "$foo". Not the variable, just the characters. Also, you have to escape single-quotes within single-quotes, but not single-quotes within double-quotes, etc. I answered this question before here.

As for your second question, they're both wrong. It should be:

echo "<a href='". $link ."'>Click Here</a>"

or, better yet:

echo "<a href='$link'>Click Here</a>"

or, better still, a templating engine like Smarty TPL.

0

精彩评论

暂无评论...
验证码 换一张
取 消