Double quotes--->"$a" interpretes variables.
single quotes--->'$a' does not.Alright till now
MyQuestion:
what if I use "'$a'"?
Note:want to know behind the scene details.
Detailed Explanation:
I faced a major problem because of this when I used it in a foreach loop:
The following example gave me incorrect option value. For example, value it renders is UX if original is UX developer
echo "<option value=".$item['m_designation'].">".$item['m_designation']."</option>";
this example gave me correct option value. For example,value it renders is UX developer if original is UX developer
echo '<option value="'.$item['m_designation'].'"> '.$item['m_designation'].' </option>';
Hope I am clear.
Update:
I got the desired result but I don't know the logic behind it. I have tried it and done it successfully, but I wanted to know what's happening behind the scene. I think people have misread my question.
The use of ' and " for strings only changes when they are the outer container of the entire string - a different quote inside that is just treated as a plain character with no special meaning, therefore "'$var'" uses the rules of " (parsing variables), whereas '"$var"' would literally output "$var" as it uses the rules of ' (no parsing of variables).
Summary:
When you do "''" or "\"\"" the quotes inside the string are not parsed by PHP and treated as literal characters, the contents of such quotes will have the same behaviour in or out of those quotes.
You'll have a string that uses double quotes as delimiters and has single quotes as data. The delimiters are the ones that matter for determining how a string will be handled.
$a = 'test';
echo '$a';// prints $a
echo "$a";// prints test
echo "'$a'"//prints 'test'
double quotes checks the php variable and echo the string with php variable value
example echo "wow $a 123"; //prints wow test 123
single quotes print whatever in the single quotes
example echo 'foo $a 123';//prints foo $a 123
Your 'faulty' (first) string was missing the single quotes ':
echo "<option value='".$item['m_designation']."'>".$item['m_designation']."</option>";
^ ^
Your problem is that you confuse the quotes in your HTML with the quotes in the PHP.
$a = 1;
$b = '"$a"';
echo $b;
# => "$a"
$a = 1;
$b = "\"$a\"";
echo $b;
# => "1"
I'd advise you to simply never use string literals, as (especially in PHP) there are a lot of unexpected and weird edge-cases to them. Best is to force an interpreter (which also only works with double quotes:
$a = 1;
$b = "\"{$a}\"";
$c = "{$a+2}";
echo $b;
# => "1"
echo $c;
# => 3
It seems your question is more directed toward the output PHP produces for HTML formatting. Simply, single quotes in PHP represent the literal value:
$a = 1;
$b = '$a';
echo $b;
//$a
$a = 1;
$b = "$a";
echo $b;
//1
$a = 1;
$b = "'$a'";
echo $b;
//'1'
If you want to output HTML, you can use heredoc syntax. This is useful when outputting more than one line containing variables:
$name = "Bob";
$age = 59;
echo <<<EOT
My name is "$name".
I am $age years old.
EOT;
//My name is "Bob"
//I am 59 years old.
Related
i read string documentation on PHP and found out that Single quoted strings will display things almost completely "as it is." Variables and most escape sequences will not be interpreted except \' and \\
I wanted to display a hyperlink whose address should be http://localhost/kk/insert.php/?id="4"
i tried the following code
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=".$id."'>edit</a>";
But it's displaying http://localhost/kk/insert.php/?id=4 (there are no double quotes surrounding 4)
However, i accomplished the result by using
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
My question is that single quotes does interpret \" escape character. So why the first code is not displaying double quotes (that are placed inside single quotes). What am i missing?
You shouldn't have quotes around the integer. Your url should be
http://localhost/kk/insert.php/?id=4
which is accomplished using the following code:
$id = 4;
echo 'edit';
You're dealing with TWO languages there. PHP is doing the echo, and the " quotes are parsed/removed by PHP. Then there's the ' quotes, which are used in the HTML to delimit the href attribute.
With your escaped second version:
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
^--php ^--html ^^--escaped for PHP
Normally that " before $display_result would TERMINATE the PHP string you've been echoing. But since it's been escaped (\"), the escape tells PHP to treat that quote as plaintext, and NOT as a quote. So the PHP string continues, and when this code actually executes and is output from your server, the browser will actually see:
<a href='http://localhost/kk/insert.php/?id="XXX"'>edit</a>
The interpretting difference between single quote and double quote you found is this:
$a = 4;
echo '$a' . "$a"; // $a4
// '$a' just prints `$a`
// "$a" prints `4`, it's interpretted
// alternatively "\$a" prints `$a`
As for the escaping. If your string delimiter is a single quote then you don't need to escape double quotes, and vice versa.
$a = "don't";
// vs
$a = 'don\'t';
$a = '"quote"';
// vs
$a = "\"quote\"";
To do it with your first example, just do :
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=\"".$id."\"'>edit</a>";
<?php
$s = "pa99";
$s++;
echo $s;
?>
The above code outputs to "pb00"
What i wanted was "pa100" and so on.
But also in case its "pa", I want it to go to "pb" which works well with
increment operator.
You are, as Michael says, trying to increment a string - it Does Not Work That Way (tm). What you want to do is this:
<?php
$s = "pa"; //we're defining the string separately!
$i = 99; //no quotes, this is a number
$i++;
echo $s.$i; //concatenate $i onto $s
?>
There's no automated way to increment a string (aa, ab, etc) the way you're asking. You could turn each letter into a number between 1-26 and increment them, and then increment the previous one on overflow. That's kind of messy, though.
To separate the integer from the string, try this:
PHP split string into integer element and string
From the docs:
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.
<?php
$s_letter = substr($s,0,2);
$s_number = substr($s,2,9);
$s_letter++; $s_number++;
$s_result = $s_letter.$s_number;
echo $s_result;
?>
I ran into a block of code that executes print with double quotes around the argument. The argument contained a variable that was seemingly escaped by a dollar sign. Is that how a variable is called inside double quotes in php?
print("$$owed");
Here's the full block from the source:
<html>
<head>
<title>Loans</title>
</head>
<body>
<?php
$interest_rate = .14;
function YouOweMe($cost, $interest_rate) {
$weekly_payment = ($cost*$interest_rate);
print "You better pay me $$weekly_payment every week, or else!";
}
<font color="#000000">YouOweMe($cost, $interest_rate);
?>
</body>
</html>
I had to strip the numbers. So annoying.
Anyway, ... What doesn't make sense to me is that $$owed is supposed to, what? Create a new variable from a separate variable that contains a string 'owed'? That doesn't seem practical in any situation. Isn't $$owed just to get a dollar sign before the amount?
Here is an example to understand variable variables :
<?php
$var = "test";
$test = "hey !";
echo "$$var"; //$test
echo "${$var}"; //hey !
echo '$$var'; //$$var
?>
Edited according to comments.
In PHP, a variable is escaped with $ when inside a string defined with double quotes. This does NOT work with single quotes.
$string = "world";
echo "Hello ${string}";
#### outputs "Hello World"
That is how you put a variable into a string (you need the double quotes).
What you have is variable-variable. You can call a variable $foo by using a string with foo in it.
$string = 'foo';
$foo = 'hello world';
echo "I say, ${$string}";
Would output "hello world.
There are a couple of ways to use variables inside double quotes, some common ways are
print("$owed") will print the value of $owed
print("$$owed") is called a "variable variable" (as linked previously)
$owed = "test";
$test = 16;
print("$$owed");
will print out "$test".
Another use of this comes in the form of print("${$owed}"), which takes the value of $test and uses it as the variable name.
I strongly advise you to use single quotes and concatenate the variables needed, as it saves the time for evaluating variables in out, e.g.:
$owed = 42;
print('The value is: ' . $owed);
lg,
flo
I would like to know when and why should I use {$var}
echo "This is a test using {$var}";
and when (and why) should I use the simple form $var
echo "This is a test using $var";
You would use the latter when a) not accessing an object or array for the value, and b) no characters follow the variable name that could possibly be interpreted as part of it.
http://php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you
write $$a[1] then the parser needs to
know if you meant to use $a[1] as a
variable, or if you wanted $$a as the
variable and then the [1] index from
that variable. The syntax for
resolving this ambiguity is: ${$a[1]}
for the first case and ${$a}[1] for
the second.
The brackets allow you to remove ambiguity for the PHP parser in some special cases.
In your case, they are equivalent.
But consider this one:
$foobar = 'hello';
$foo = 'foo';
echo "${$foo . 'bar'}"; // hello
Without the brackets, you will not get the expected result:
echo "$$foo . 'bar'"; // $foo . 'bar'
For clarity purposes, I would however strongly advise against this syntax.
If you write
echo "This is a test using $vars"
You do not get content of $var in result text.
If you write
echo "This is a test using {$var}s";
Everything will be OK.
P.S. It works only with "" but not for ''.
The {} notation is also useful for embedding multi-dimensional arrays in strings.
e.g.
$array[1][2] = "square";
$text = "This $array[1][2] has two dimensions";
will be parsed as
$text = "This " . $array[1] . "[2] has two dimensions";
and you'll end up with the text
This Array[2] has two dimensions
But if you do
$text = "This {$array[1][2]} has two dimensions";
you end up with the expected
This square has two dimensions.
Very basic, but would like to know the difference/security ramifications etc of using " vs. '.
Can someone provide an example that explains when to use each one?
There are a lot of subtle differences, you'll want to read the php documentation to get a lot of the details, but the important detail are:
Double quotes are parsed whereas single quotes are literals.
You can use variables inline with double quotes, but not with single quotes.
There are some catches though:
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
Single quotes are slightly faster.
When a string is enclosed in double quotes, then escape sequences such as \n and variable identifiers such as $var are interpreted.
See the PHP strings manual for specific details and examples.
The biggest one is this. Inside double-quotes, you can include variables, but inside single quotes, the variable name will be literal:
$var1 = "hello";
// this will echo "hello world"
echo "$var1 world";
// this will echo $var1 world
echo '$var1 world';
Using double-quotes becomes extremely useful in a number of situations, expecially when you place {} around the variable names. Here are some examples (certainly others can give you more examples):
// array elements
echo "Element 5 is {$myArray[5]}";
echo "Element 2 subelement 3 is {$myArray[2][3]}";
//
// a dynamic key
$value = "thing";
$someValue = $myArray["some{$value}"]; // returnd $myArray[something]