Is there any difference between typing:
<?php echo $_SERVER[REQUEST_URI] ?>
or
<?php echo $_SERVER['REQUEST_URI'] ?>
or
<?php echo $_SERVER["REQUEST_URI"] ?>
?
They all work... I use the first one.
Maybe one is faster than the other?
Without quotes PHP interprets the REQUEST_URI as a constant but corrects your typo error if there is no such constant and interprets it as string.
When error_reporting includes E_NOTICE, you would probably get an error such as:
Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in <file path> on line <line number>
But if there is a constant with this name, PHP will use the constant’s value instead. (See also Array do's and don'ts)
So always use quotes when you mean a string. Otherwise it can have unwanted side effects.
And for the difference of single and double quoted strings, see the PHP manual about strings.
The first one is wrong - you're actually looking for a constant REQUEST_URI that doesn't exist. This will generate a notice-level warning.
There's no difference between the other two.
There is a difference between single and double quotes in PHP string handling. A string enclosed in double quotes will be evaluated for embedded variables and escape characters (e.g. \n); a string enclosed in single quotes won't (or not as much).
So, for example,
$hello = "world";
echo "Hello $hello!\n";
echo 'Hello $hello!\n';
echo 'Done';
will output
Hello world!Hello $hello!\nDone
In situations where you have no escape characters or embedded variables, it is slightly more efficient to use single quotes as it requires less processing of the string by the runtime. However, many people (me included) prefer to use double quotes for all strings to save confusion.
As a caveat to Gumbo's answer the third representation - double quotes - actually makes PHP look for variables inside that string. Thus that method might be a little slower (although in a string of 11 characters it'll be negligible - it's better practice not to make PHP do that however).
When PHP comes across plain strings being used as array keys it checks if there is a constant with that name and if there isn't it defaults it back to an array key. Therefore, not using quote marks causes a slight performance hit and there is a possibility that the result will not be what you expect.
$_SERVER[REQUEST_URI]
is syntatically incorrect and AFAIK will not run on a default installation of PHP5. The array index is a string so it needs to be passed on strings. I know PHP4 converted undefined constants to strings inside the square brackets but it's still not good practice.
EDIT: Well unless you define a constant called REQUEST_URI, which you haven't in your example script.
$_SERVER['REQUEST_URI']
is the standard method and what you should be using.
$_SERVER["REQUEST_URI"]
also works and while not wrong is slightly more work for the PHP interpreter so unless you need to parse it for variables should not be used. (and if you need to do so, you need to rethink that part of your program.
Related
I've been trying to find solution somewhere for this possibly simple fix but, I haven't been able to surprisingly.
How is it possible to stop PHP from assuming a variable is a part of a string. E.g.
The line of code is $string = "slfnnwnfkw49828323$dgjkt^7ktlskegjejke";
how do you stop PHP from thinking '$dgjkt' is a variable within the string when it's really a part of the full string as characters. Thanks
Use this string like $sting = 'slfnnwnfkw49828323$dgjkt^7ktlskegjejke'
You have to use ' instead of " otherwise php tries to find any variables inside your string
Read the manual.
The most important feature of double-quoted strings is the fact that
variable names will be expanded. See string parsing for details:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The
simple syntax is the most common and convenient. It provides a way to
embed a variable, an array value, or an object property in a string
with a minimum of effort.
The complex syntax can be recognised by the curly braces surrounding
the expression.
I am new to Laravel and I am having this question.
I tried out this line of code and it works fine: return redirect("/cards/{$note->id}");
But when ever I try to use the single quotes, it does not work: return redirect('/cards/{$note->id}');
How can I solve this problem ?
What you are doing first is called variable interpolation or string interpolation. You can read more about it here, on PHP docs and here, on Wiki.
It's a feature in PHP that allows you to pass a string and have variables/placeholders inside interpreted.
In your second example you are using single quotes, which does not provide this feature, so you will have to break it up and add the variable manually to the string:
return redirect('/cards/' . $note->id);
If you are interested in a more elaborate explanation and the performance behind it then you can read more on this answer here by Blizz
He concludes that:
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
You should use "/cards/{$note->id}" or '/cards/'.$note->id
The most important feature of double-quoted strings is the fact that variable names will be expanded.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
From PHP documentation
Use it like that:
return redirect('/cards/'. $note->id);
With either single or double quotes
I'm working to integrate a plug-in into a PHP web application, and one line of the code puzzles me:
$sql = "update inventory set qtyleft='$qtyleft',price='$price',sales=sales+'$sales',qtysold=qtysold+'$qtysold' where id='$id'";
mysql_query($sql);
where $qtyleft, $price, $sales, $qtysold and $id are all variables.
I'm not very familiar with PHP, but I always thought string concatenation in PHP is done by using the . operator and it seems to me that the code above is just a long string without actually putting those variables to the SQL query. Is that the case?
In PHP, double quote (") delimited strings will evaluate variables in them.
$foo = 42;
echo "The answer for everything is $foo"; // The answer for everything is 42
This specific example is very bad because you shouldn't include variables directly in an SQL query, and shouldn't use mysql_query in new code.
See more:
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
See Variable Parsing section of the Strings manual page.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
If you use single quotes for a string, the variables will not be interpolated. If you use double quotes, they will be.
The code you mentioned will work in PHP without any issues. Please refer PHP Manual for more details.
Other issue that you might need to look forward is the function mysql_query is depreciate. Please refer here. Which gives me a feeling that the plugin you are going to is use not maintained correctly. And one more problem is, its not a good practice to pass the variable directly in the SQL query do to possible security issues
Some call it "variable interpolation". It is explained on the Variable parsing section of the manual page about strings. It helps to read the entire page and also the user comments.
The basic idea is that for strings enclosed in quotes (") and on heredoc blocks, PHP searches for variables inside the string when it needs to use it and replaces them with their values at the moment of the execution. This means the same string can render to different values in different moments of the script's execution.
This is just syntactic sugar, it doesn't change the way the code behaves and any string that contains variables inside can be rewritten using the string concatenation operator (.). Usually this syntax produces shorter source code. Sometimes the code is easier to read this way, other times it is harder because the complex expressions (array access, f.e.) need to be enclosed in curly braces ({ and }) inside the string.
I have a (probably) very simple and easy to answer question, which I cannot find the answer to anywhere, perhaps it is too simple, and I am not well-versed in php.
I am using a script written by someone else, and they sometimes use single quotes within the square brackets, [ ], and sometimes not. What is the correct way?
For example, is it best written [data] or ['data']? I am a perfectionist and this is driving me crazy to know the proper method.
Echo "Name: " .$ratings['name']."";
$current = $ratings[total] / $ratings[votes];
Echo "Current Rating: " . round($current, 1) . "";
You must always use single or double quotes when accessing an array element.
I asked in ##php on freenode, and they believe this quirk existed since PHP4.3 (god knows why), but right now when PHP comes across $array[value], it firstly tries to look for a constant named value, and if it is not define()'d, it treats the expression as $array["value"] and spit a Notice in PHP4. In PHP5, this has been upgraded to a warning.
In short: Don't use it. It confuses yourself.
Definitely use the quotes. Additionally, there is a subtle but important difference in PHP between single and double quotes strings. A single quoted string is actually faster, because it is treated as a literal, whereas a double quoted string gets interpreted, which takes O(n) time. Example:
$test = 'world';
echo 'hello\n$test';
yields hello\n$test
$test = 'world';
echo "hello\n$test";
yields
hello
world
Either double or single would work. Personally I prefer single.
PHP is very forgiving and only spits out a notice if no quotes are given to an index of the array.
Both are working fine. I'm just curious how php parse the two. Do they have difference on speed, efficiency, etc. Why does php allow us to use both?
Difference is that the first ('literal') is a string key and that the second one is undefined constant. PHP allows you to use both because devs tried to fix bad code of people who weren't paying attention while reading the docs. There's a difference in speed since the second one will raise a warning - undefined constant. Basically, don't use the second one.
if you are using just literal php recognizes this as a constant. So it try to find that constant, and if it fails - it just assumes that your desire was using string literal 'literal'. But, to indicate that it doesn't found the constant it raises Notice level error.
So, using just literal have tweo drawbacks:
If you have constant literal defined - you'll get it's value (and this is a correct usage), not string 'literal'
You'll receive a Notice if you don't have such constant.
So, don't use just literal unless you have a constant with that name defined.
$arrayName[literal] is bad because if you have constant named literal, you'll get unexpected results. When it's no constant named literal, php transforms literal to string 'literal'
http://php.net/manual/en/language.types.array.php
Array do's and don'ts
*Why is $foo[bar] wrong?*
Always use quotes around a string literal array index. For example,
$foo['bar'] is correct, while $foo[bar] is not. But why? It is common
to encounter this kind of syntax in old scripts:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
This is wrong, but it works. The reason is that this code has an
undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for
such code, have the same name. It works because PHP automatically
converts a bare string (an unquoted string which does not correspond
to any known symbol) into a string which contains the bare string. For
instance, if there is no defined constant named bar, then PHP will
substitute in the string 'bar' and use that.