Perhaps this is a petty question, but consider the following PHP code:
$a = "foo1"; $b = "foo2"; $c = "foo3";
echo $a, $b, $c;
echo $a . $b . $c;
echo "$a$b$c";
aren't these three statements equivalent. What's the difference.
What if one cannot decide whether to use one or the other?
The first one simply echoes out 3 values in a single call. The other two do string concatenations and output the result of that operation. In other words, if you were doing this a few zillion times in a row, the first version would probably be slightly faster, because there's less string operations going on.
That being said, even if you reduce string operations in PHP, the output produced by the echo statements will still be tacked onto the end of an output buffer, and stuffing in a single larger string may be more efficient than multiple smaller strings.
In the grand scheme of things, there'll probably be very little difference between any of those versions, so go with the one that makes the most sense to you, and is easiest for maintenance down the road.
They are mostly equivalent, I would assume that the only real difference would be on performance of how it executes. This may become insignificant or nonexistent if you use a php optimizer.
If I was to guess, I would say that echo #1 is fastest, followed by echo #2, and lastly echo #3.
Why I say this?:
echo #1:
plays directly off of the language construct that it is and simply spits out the variables.
echo #2:
must first concat the strings together and then echo it out
echo #3:
Must first search through the string and replace what it finds with what the variable is. Which would most likely be the most expensive operaion to handle.
Additional note:
You should ALWAYS use single quotes when putting strings into variables unless you explicitly want variables replaced on the inside. Thus your first line:
$a = "foo1"; $b = "foo2"; $c = "foo3";
Should be:
$a = 'foo1'; $b = 'foo2'; $c = 'foo3';
Just a note about the third method:
When using variables in double quotes, I am in the habit of using curly brackets because they escape array-based variables:
echo "{$a}{$b}{$c}";
If $c were an associative array and you wanted to output some element of it, the statement would then be:
echo "{$a}{$b}{$c['foo']}";
Sometimes this results in neater string formatting than concatenating variables and strings together for output.
Related
eval("echo {$row11['incentive']};");
In my table column named incentive , I have values stored like a string for eg. '($workshop_sales*0.005)' and there are mutliple kind of formula stored for calculation of incentive.
I have result generated using above code in php but when I am going to store its value in any variable then it is not getting stored.
How can I store its result? is it possible or not ??
Instead of echoing inside the eval-ed code, return the value:
<?php
$workshop_sales = rand(1000, 9999);
$row11['incentive'] = '($workshop_sales*0.005)';
$result = eval("return {$row11['incentive']};");
var_dump($result);
From the docs:
eval() returns NULL unless return is called in the evaluated code, ...
And obvious eval is dangerous-statement (also from the docs):
Caution The eval() language construct is very dangerous because it
allows execution of arbitrary PHP code. Its use thus is discouraged.
If you have carefully verified that there is no other option than to
use this construct, pay special attention not to pass any user
provided data into it without properly validating it beforehand.
simply you can assign the variable to the new value inside the eval function
and use your variable later
for example :
eval('$result = "2";');
echo $result;
this will print out the value of the $result variable
PS,
you have to take a look at what #yoshi had mentioned about the dangerous of using eval
Assumption:
$workshop_sales = 15;
$row11['incentive'] = '($workshop_sales*0.005)';
Variant 1 Saving result directly (unsecure):
$foo = eval("return {$row11['incentive']};");
echo $foo; //Outputs 0.075
Variant 2 Replace variable before (should be pretty secure)
function do_maths($expression) {
eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
return $o;
}
//Replace Variable with value before
$pure = str_replace("\$workshop_sales", $workshop_sales, $row11['incentive']);
//$pure is now (15*0.005)
//Interpret $pure
$foo = do_maths($pure);
echo $foo; // Outputs 0.075
But be careful with eval(), it is evil.
Further information on When is eval evil in php?
The main problems with eval() are:
Potential unsafe input. Passing an untrusted parameter is a way to fail. It is often not a trivial task to make sure that a parameter (or part of it) is fully trusted.
Trickiness. Using eval() makes code clever, therefore more difficult to follow. To quote Brian Kernighan "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it"
I want to evaluate a mathematical operations inside the string after I get it in that string.
Here is the string
$string = "Add this two numbers [4+2+2]. And [5*3/2] will result to?"
I already get those numbers:
$f_number = "4+2+2";
$s_number = "5*3/2";
How can I evaluate this automatically using any function?
Sample:
echo anyfunction($f_number);//will result to 8
echo anyfunction($s_number);//will result to 7.5
because if I will echo directly it will just output like this:
echo $f_number;//will result to 4+2+2
echo a$s_number;//will result to 5*3/2
You can use eval. It's probably the easiest way out. Mind though that it can also be used for other expressions, because it basically executes any PHP code that is in the string.
But by wrapping it in a function, like you intended, you can at least black box it, and add safety measures later if you need to, or even switch to a different expression evaluator, without having to change all your code.
A simple safety measure would be to check if the string only contains numeric values, whitespace and allowed operators. That way it should be impossible to secretly inject actual code.
function anyfunction($expr)
{
// Optional: check if $expr contains only numerics and operators
// actual evaluation. The code in $expre should contain a return
// statement if you want it to return something.
return eval("return $expr;");
}
echo anyfunction($f_number);
In preparing MySQL statements in PHP, I came across lines of codes like this:
$somequery = "some query '$var'";
Where $var is a variable containing a string.
What is the difference with the statement using the string concatenating operator .?
$somequery = "some query " . $var;
The result string is actually the same. If there is any difference, when should I use the one over the other?
There is no difference in the output. The performance differences are negligible. Use whichever one looks nicer to you. Some prefer concatenation because syntax highlighters like it.
The value is the same, but just use one which will make your code easy to read or debug by yourself or by others you have given permission to!
For example:
<?php
$var1 = 'cow';
$var2 = 'lamb';
?>
<?=$var1,$var2?>
or should that last part be:
<?=$var1.$var2?>
The operation you're performing is concatenation. Technically you can also use a comma as well, but for clarity I would use the concatenation operator, which is a period (or dot).
Using a comma seems to be slightly faster, but this kind of speed differences are negligible. Code should always be optimized for reading (it's hard to read by definition already), only when serious performance issues are encountered you can start optimization. And even then, replacing concatenation with passing multiple arguments is not going to improve much.
Also, this works only for the echo() function. Consistency is usually good thing.
P.S. Using a space after a comma or around operators is also often recommended for readability:
<?=$var1 . $var2?>
<?=$var1, $var2?>
This might be a silly question but it struck me, and here i ask.
<?php
$x="Hi";
$y=" There";
$z = $x.$y;
$a = "$x$y";
echo "$z"."<br />"."$a";
?>
$z uses the traditional concatenation operator provided by php and concatenates, conversely $a doesn't,
My questions:
by not using the concatenation operator, does it effect the performance?
If it doesn't why at all have the concatenation operator.
Why have 2 modes of implementation when one does the work?
Only slightly, since PHP has to parse the entire string looking for variables, while with concatenation, it just slaps the two variables together. So there's a tiny performance hit, but it's not noticeable for most things.
It's a lot easier to concatenate variables like $_SERVER['DOCUMENT_ROOT'] using the concatenation operator (with quotes, you have to surround the variable in brackets or remove the single quotes in the array index; plus it just makes the string look all ugly). Plus, the concatenation operator allows more flexibility for formatting. For example, you can break up a long string literal onto multiple lines and then concatenate the different parts of it:
$blah = "This is a really really long string. I don't even know how " .
"long it is, but it's really long. Like, longer than an eel " .
"or even a boa constrictor. Wow.";
You can also use the concatenation operator to directly include return values from functions in a string literal (you can't include a function call in a double-quoted string), like this:
$blah = "This has a " . fn_call() . " result, which can't go in the quotes.";
I'm not sure I entirely understand what you're asking here, but I can say that PHP borrows a lot of things from Perl, and one of Perl's mantras is "There's more than one way to do it."
a. Yes. PHP has to parse the string for variables.
b. Because of lines like: echo 'Your Ip address is' . get_ip() . '.';
For reasons A and B.
In some cases your write less with:
$someLongVarName ="Hi";
$someLongVarName .=" there";
VS
$someLongVarName ="Hi";
$someLongVarName = "$someLongVarName there";
Addressing your last question:
Every language has multiple was of doing the same thing. Flexibility is important in every language since any given method may be better the another from situation to situation. The only thing that you should worry about in regards to this is to be consistent in your own code.