What runs faster?
Setting a default value and changing it-
$foo = "";
if($bar)
{
$foo = "someValue";
}
Or-
if($bar)
{
$foo = "someValue";
}
else
{
$foo = "";
}
You absolutely should not be bothered with performance of a single if statement.
Also, consider:
$foo = $bar ? "" : "someValue"
At a guess, the 2nd one "potentially". First one you're potentially setting 2 values. Second one you're definitely only setting one.
Its also a question though of code clarity. If you've got 2 alternatives (e.g turn left or right) then use the "else" statement. If you've got a 'normal' value vs a flag e.g http or https, then use the first one
EDIT: becose you valorize a variable in base to another one, the isset() statement is mandatory.. so the 'faster one' is the second way becose, as David said, yoo valorize the $foo var just one time.
Also consider the Anton suggestion to use the short if syntax (dont know if it speed up the execution)
P.s: if your goal is to speed up many if like that one, use the ' instead of ", becose the content inside "" is being evalutated by php (in case it contain a variable:
Related
I'm sorry the title of this question is odd. I couldn't find a good way to word it!
The idea is simple, sometimes you see PHP tests this way:
if (!a_function("something")) { }
Here you can think of it as "if not true". I sometimes see the exact same thing but with extra parenz:
if (!(a_function("something"))) { }
Why does it require the extra parenz after the bang? Don't they both essentially mean if (!true)?
For extra bonus, what are the reasons for the two styles (does this have a name?) and maybe give examples of how they would give alternate results if not used correctly.
update:
Here is an example in a PHP script I'm using, the author is testing environment variables and seems to use the styles interchangeably:
if (!(extension_loaded("iconv"))) { ... }
if (!(extension_loaded("xml"))) { ... }
if (!function_exists("json_encode")) { ... }
if (!ini_get("short_open_tag")) { ... }
I know you can't answer for the programmer here, but why would they be alternating the use of extra parenz when these small functions are right next to each other?
I happen to know that, for example, the return value of ini_get is just the number 1, and the return value of the extension_loaded functions may also just be the number 1, so it seems like there would be no difference. I'm not 100% sure there isn't some other trick to this than simple preference or order of operation.
update 2:
I understand parenz can be used for either clarity, or order of operations, but I'm not convinced it is only personal preference beyond that.
In my example above, everything depends on what is returned by the functions that are being tested.
It's my understanding that by wrapping a statement in parenz, PHP will force it into a bool. But when it's not in parenz, could there be a return value that breaks the code without using the parenz around it to force a bool?
If people say, in my example code above, that there is nothing but personal preference going on, then I'll just have to accept that, but I have my doubts.
the parenthesizes are used in case if there are more than 1 logical operator with different precedence, to indicate that "!" operator must be applied after all other operators have been processed. For example:
if(!($var1 < $var2))
First will be checked if $var1 is less than $var2, and after that will be checked if the result is false.
If use that:
if(!$var1 < $var2)
then firstly will be checked if $var1 is false and the result will be compared to $var2, that simply do not make sense.
It's not required. It's a matter of personal preference. Sometimes you like to have extra parens to be EXTRA certain of how the expression will be evaluated.
if(a or b and c)
is confusing.
if ((a or b) and c)
is much more clear.
if(a or (b and c))
is much more clear.
They both work, but some people might have different opinions on which one is more readable.
Parenthesis are not required in the given case, but they can be if, for example, you also assign a variable at the same time :
if (($myVar = myFunc()) !== false) {
// Doing something with $myVar, ONLY if $var is not false
}
While, in the following case, it will change the logic
if ($myVar = myFunc() !== false) {
// Here $myVar = true or false instead of the wanted value
}
if( !(should_return_trueA() && should_return_trueB())) {
// at least one have returned false
}
esentially is the same as:
if( !should_return_trueA() || !should_return_trueB() ) {
// at least one have returned false
}
It's, in my case, a practice to avoid mistaken/ommited exclamation marks. Useful, when building more complex conditions and looking for all-false or all-true result.
I'm fairly new to PHP and still don't know some of the most basic basics of PHP so bear with me.
When writing a script; IE: (Plz ignore syntax errors)
if isset($_POST['name']) {$Name = $_POST['nsme'];}
When using this name in the page, which way is better and loads faster??
A:) echo $Name. ' went to the river';
B:) echo $_POST['name']. 'went to the river';
Obviously this is a fictional example, I'm just wondering which way is better whether it be an echo or any other function and if anyone wouldn't mind chiming in on this, I'd be most appreciative and I thank you all once again.
Obviously
echo $_POST['name'].' went to the river';
would be faster, as you are skipping one step of assigning the post variable to a php variable.
echo $_POST['name'].' went to the river';
Will be faster as you are skipping one step.
However if you need to use $_POST['name'] multiple times, second approach will be better.
If you care about speed don't worry you can use any of them ,deference significantly low but creating variable which is used only once is not a good idea
However if you are doing
$Name = $_POST['nsme'];
and using $name variable i am sure you want to read about Singleton variable
and if you are using $name at other place too its perfectly
A direct variable access is always faster. At least the zend lexer has not recognize for dimensions...
At least for multiple uses...
(use always an isset()-check at least else you'll have notices.)
If you have var $foo and make:
$bar = $foo;
It doesn't create another copy of $foo in memory until you change $foo or $bar so you will have almost same var for both.
You will have same speed, but $bar will look better than $_POST['bar'] and with it easier to work.
Netbeans seems to suggest too many assignments is quite bad and should be changed.
i.e.
$foo = ' bar ';
$foo = trim($foo);
Should better coded as
$foo = ' bar ';
$trimmed_foo = trim($foo);
Is this acceptable? If so why? I know I can switch this particular hint type off in setting, but just checking if someone spotted anything for this.
Ths is a new warning, circa mid 2012.
Since you used the trim example I'm guessing that you have read this https://blogs.oracle.com/netbeansphp/entry/several_new_hints, which tries to explain the warning. My take on this warning is that it's trying to warn you about accidental reuse of a variable. As such it is very handy. In the trim case you give it seems a bit heavy handed. If the reassignment is on he following line, it's probably not accidental.
Ideally the variable name should describe the contents. If you are repeatedly assigning to the same variable, it suggests that the variables contents are not well defined.
Additionally, if your code has something like this:
$foo = ' bar ';
// some code, mybe 100 lines of it
// now do something with $foo
What happens if you update the code to add $foo = trim($foo); up above? You break the code below.
Those variants make no difference. If anything the first is better because it avoids cluttering the scope with variables.
I think what the warning really means is that you should try to do
$foo = trim(' bar ');
directly (or whatever $foo is really being set to in the first place), instead of storing it in a temporary. Of course, this isn't always possible.
If you don't like this hint, you can simply deactivate it in Tools -> Options -> Editor -> Hints -> PHP -> Immutable Variables
IMHO, first way is ok for more performance comparing second.
On the other hand, second approach can be more helpful if you need more descriptive variables. Also this may help more if multiple persons are working on same project.
I'm curious is there a way to write a shorthand setter in PHP. My primary quest when writing code is to make it as tight as possible and I think the following is kind of cumbersome:
$value = "Which array do I go in?";
if(true)
$arr_1[] = $value;
else
$arr_2[] = $value;
Is there a better way to write that? I tried to use the shorthand if:
(true)?$arr_1[]:$arr_2[] = "Which array do I go in?";
But that doesn't seem to work. Anyone have any cool tricks for this type of situation?
Thanks!
There is no shorthand for what you are trying to do. Also you should realize that making code "as tight as possible" often comes at the cost of readability.
EDIT: There is some ugly hacks to do what you want, but I would strongly recommend against. E.g.:
$GLOBALS[cond ? 'varname1' : 'varname2'] = $value;
Another hack would be:
$arr = ($cond ? &$arr_1 : &$arr_2);
$arr[] = 'Which array do I go in';
it's two lines but it doesn't require global and would work in a function. However for readability it is probably better to use an if statement. (Note: the & is making a reference to the variable, which is why this works). Another (which might make you understand HOW the ternary operator works) would be:
$cond ? $arr_1[] = $value : $arr_2[] = $value;
You see the ternary operator only evaluates (runs the code path) of the successful evaluation (on the right side of the ? if true, on the right side of : if false). However if you think this is faster than using 'if' you are wrong, your less 'tight' code will actually perform better.
Another option (e.g. if you can't/don't want to use globals).
${$cond?'arr_1':'arr_2'}[] = $value;
Earlier today I tried to do this:
Example 1:
<?php
echo $myVar || "rawr";
?>
I thought this might print out $myVar if it was set, and print "rawr" if not.
It printed a 1, I assume this is the result of the OR test.
What I then tried was this:
Example 2:
<?php
if ($myVar)
{
echo $myVar;
}
else
{
echo "rawr";
}
?>
Which is what I was trying to accomplish.
I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it - been spending some time on the bash shell recently :)
Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1?
PHP 5.3:
echo $myVar ?: 'rawr';
Pre 5.3:
echo $myVar ? $myVar : 'rawr';
If $myVar may not be set you'd have to use isset($myVar) and $myVar as the condition (which then wouldn't work with the shorthand ?: syntax, as this would echo 1 if it was set, rather than the value).
echo (isset($myVar) and $myVar) ? $myVar : 'rawr';
PHP is notoriously inelegant in this department, and there really is no good way of making this test.
As a general solution, you 'd need to use the ternary operator as in empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios:
1. Your own variable
In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator).
2. Inside an array
If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that's what everyone does).
If the array is one under your jurisdiction but it comes from an external source, you can use the "add the defaults" trick:
$incoming = array(...);
$defaults = array("foo" => "bar");
// Inject the defaults into $incoming without overwriting existing values
$incoming += $defaults;
At this point you know for a fact that every key inside $defaults also exists inside $incoming.
In PHP 5.3+ it is possible to leave out the second argument:
echo $myVar ?: 'rawr';
This is probably closest to what you want.
Try this:
echo $myVar = ($myVar) ? $myVar : 'rawr';
or
echo $myVar ? $myVar : 'rawr';
I think you want to use something like var_dump($varname) or isset($varname) ?
it's matter of operator precedence. you can't do that.
two points as a food for thought
if $myVar is not set, you'll get an error message, not "wawr";
by the time you're going to echo some variables, every one of them should be defined and have value. That will make your template clean and readable.
Try
echo ($myVar != null ? $myVar : "Rawr!");