php singlequote not working on sprintf properly - php

I use sprintf() on my program to output some tabs and newlines. I noticed a part of my program not working properly.
As I inspected the part that isn't working, I noticed that I used a single quote ' instead of a doublequote " and the program actually outputs a \t instead of a inivisible tab space.
I thought the two are similar and the reason for having two delimeters for php is for us to be able to insert single or doublequote in a string or echo them without inserting escape characters.
Would there be a difference in assigning variables aside from the one I discovered
$a = "qq";
$b = 'qq';
Would they be stored in the computer's memory in a different manner?

you can refer to the manual that specifies that single quotes in php consider most escape sequences as litterals, contrary ot double quotes:
http://php.net/manual/en/language.types.string.php

single quote is faster than double
double quote can parse php variable. i.e. $a=2; and if you use echo "a is: $a"; then it will print a is: 2 but single quote will print a is: $a

if you use single quotes for the format string (like you should do, since there
aren't any variable conversions to do as long as you don't need any special chars),
the given examples won't work because of the backslash before the $ (needs to be
escaped in double quoted strings - but not in single quoted!) http://php.net/manual/en/function.sprintf.php

Related

PHP - Why single-quoted variables inside doubles are still parsed

Normally, when variables in PHP are enclosed in single quotes, they are treated as strings, i.e
echo '$variable';
will actually echo the word $variable onto the screen.
So why is it then that this string is parsed:
echo "'$variable'";
That code actually does echo the value of the variable. Why is that? It's still inside single quotes, so why does it still get parsed?
The string is wrapped in double quotes -- the single quotes are part of the content of the string, not part of the string's delimiter. Therefore the single quotes have no semantic meaning whatsoever.
Your question indicates that you may have a fundamental misunderstanding of strings. This is OK! Strings are surprisingly complex entities, and will only get more complex if you learn lower level languages like C. I would suggest you spend some time reading up on strings both in general as well as within PHP. A few quick google searches will honestly be better than a curated list for this task.
Because the single quotes are inside double quotes. Anything inside double quotes gets evaluated. So, your echo statement is passed a string inside double quotes.
This string is evaluated then output. It contains single quotes and a variable.
Try this instead:
<?php
$var = 10;
echo '"$var"';
?>
Because it's in double-quotes as well. The outer most layer of quotes denotes what kind of string it is.
It is simply a double quoted string that contains two single quote characters. Once they are in the double quotes, they have no meaning to the parser.

PHP str_replace doesn't work as expected

I'm trying to use str_replace to correct a filepath as shown below:
$a="F:\xampp\htdocs\yii\get_smart\Music\mix\English\1636464449";
$a=str_replace('\\','/', $a);
echo $a;
returns:
F:
mpp/htdocs/yii/get_smart/Music/mix/Englishs6464449
Can someone please tell me what I'm doing wrong?
My PHP version is 5.3.8
Use single quote for define $a
$a='F:\xampp\htdocs\yii\get_smart\Music\mix\English\1636464449';
the problem is not str_replace but the string defined within double quotes. The backslashes escape the x and other character after it.
This is happening because your string is in double quotes, so the \x is being parsed as a character.
Actually, it's trying to read \xam as a character. Docs: http://php.net/manual/en/regexp.reference.escape.php
Put your string in single quotes (or escape the slash before the x).
Your problem is that the first string has some escaped sequences. For example \xam has a meaning in php. It looks like \16 might also mean something. You should echo $a before you do the str_replace and see what you get.

query MySQL with PHP but database column has a $

I'm building an application around a database(which was built by someone else, so changing it is not an option). I'm querying the database for values which was working fine until I came across a column in the database that has a $ in it.
The code I'm trying to get to work is...
$avgprice=mysql_result($result1,$i,"avg$cwt");
Try to escape $ sign or use ' instead of ":
$avgprice=mysql_result($result1,$i, "avg\$cwt");
// or imho better way to do it:
$avgprice=mysql_result($result1,$i, 'avg$cwt');
PHP strings:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
and
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Use single quotes ' instead of double quotes " to prevent PHP from trying to replace the assumed variable.
$avgprice=mysql_result($result1,$i,'avg$cwt' );
PS: Maybe consider using PDO or mysqli instead of the plain mysql_X functions.
Use single quotes.
$avgprice=mysql_result($result1,$i,'avg$cwt');
Double quotes interpolate (expand) variables. Single quotes do not. Good practice in PHP is to only use double quotes if you want to interpolate variables in the string. Single quoted strings are processed faster because the interpreter doesn't have to look for variables.

Single Quotes Instead of Double Quotes?

Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?
It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.
Is there something I am missing?
For examples:
HTML
<a href='http://google.com'>Google</a>
PHP
<? echo 'Hello World!'; ?>
ASP.NET
<form id='myForm' runat='server'></form>
Technically, in PHP single quotes are faster since you don't need to parse the content within.
edit:
So double quotes are automatically converted to single quotes, but if you have variable substitution going on within your double quoted string, that's when you take a performance hit:
http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes
Either ways, to answer OP's question while the jury is out on this, play it safe (TM) and use single quotes :)
In HTML, I don't think the "why" can be answered in anything but the obvious case: single quoted strings are more convenient when the string contains double quotes, and vice-versa.
In PHP, single quoted strings are more convenient when you don't want any special interpolation or escape characters.
My personal preference is always use double quotes in HTML, and to always use single quotes in PHP unless I need interpolation. Thus, I consider the single quoted strings to be "constants" of sorts in PHP, while the double quoted string implies something else is going on.
<opinion>But why do some people whimsically choose between the two? Probably because they are undisciplined and subsequently not very good programmers.</opinion>
From W3C: http://www.w3.org/TR/html4/intro/sgmltut.html
All attribute values [should] be delimited using either double quotation
marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39).
Single quote marks can be included within the attribute value when the
value is delimited by double quote marks, and vice versa.
Strings in PHP follow the same principle - interchangeable single/double quotes.
I would say that for most people, single and double quotes are treating and used interchangeably without a real understanding of the difference.
Both are used to create/delineate strings.
'Hello'
"Hello"
Both are strings and are treated the same when used in this circumstance.
The difference in in processing. Technically, single quotes strings are not processed when created and stored in to memory. They are taken as is and made into strings.
Double quoted strings are processed when created and stored into memory. That is why you can put a variable into a double quoted string and it's value will be put in, but in a single quoted string the literal variable is put in. For most things, there is not a real difference if you sing a single or double quote except when creating strings with variables, function calls, etc and for saving some milliseconds in processing.
Basically, the choice is yours. But for readability & maintainability, pick one form & stick with it.
I find the use of single quotes advantageous when I'm embedding html into strings, mainly when dealing with templating. Here is an example:
public string EmailTemplate =
#"<div style='color:red'>HEY {0}! BUY MORE STUFF</div>"
// later in code
instanceOfStringBuilder.AppendFormat(EmailTemplate, firstNameVariable);
I don't have any hierarchy in my mind for whether single or double quotes are "better." It is purely a matter of being consistent and having something that programmatically works.
I agree with #stillstanding on the issue of interchangeability within HTML. However, in PHP I use double quotes in instances where I need a variable within a string parsed. Consider this:
<?php
$id = 123;
echo "Your id is $id<br />";
echo 'Your id is $id';
?>
This will output
Your id is 123
Your id is $id

learning about single and double quotes (.),("), and (')

Can you tell me what is the different using (')single quotes inside (")quotes and (")quotes inside (')single quotes? and at concat, what is the meaning of this '".$bla."' I still can not distinguish them.
In SQL, anything with single quotes is considered a text based data type.
SQL uses double quotes for escaping keywords and non-ASCII characters.
This:
'". $bla ."'
..is PHP syntax. $bla is a PHP variable, the period is a string concatenation character (which is why there's one on both sides). So in this example, the content of the $bla variable is being concatenated into a string, where it will be surrounded by single quotes.
The main difference is the anything in a double quote is evaluated and anything in a single quote is not. There has been some discussion that it is better to use single quotes than double quotes so that PHP does not need to evaluate every aspect of the line to determine if it is a variable or not:
$good = 'really good';
echo "this is not $good"; //bad
echo 'this is' . $good; //good
It just keeps thing running faster and keeps the code looking cleaner.

Categories