PHP Initialising strings as boolean first - php

I'm in the habit of initialising variables in PHP to false and then applying whatever (string, boolean, float) value to it later.
Which would you reckon is better?
$name = false;
if (condition == true) {
$name = $something_else;
}
if ($name) { …do something… }
vs.
$name ='';
if (condition == true) {
$name = $something_else;
}
if (!empty($name)) { …do something… }
Which would you reckon can possibly give better performance? Which method would you use?

At first glance - your $condition==true is pointless since $condition is well enough.
Second - if you're not sure what type will be variable, but you want to initialize it (that is - indeed - a good habit), use null - since false points to certain data type - bool data type, while it's not correct and person who reads your code may be confused.

Both values '' as false have meaning.
I would suggest using null as the default value. Since that actually does not (and should not) 'mean' anything.
This will also allow you to test is_null($var) to make sure something actually set a value to your variable.

Take a look here Basic php benchmarks.I usually use null. A must know here also.

Well what I think giving it Boolean value is better. It won't make much difference when you compare code running on a very powerful system.
but when it comes to system performance then it all depends upon the size of datatype you are using. boolean uses 1 bit of data. So, it is more convenient to use, and faster also.
Adding to other answers, better use null.

I think irrespective of your above two choices the performance of an if-statement depends on whether its condition has a predictable pattern i.e. BRANCH PREDICTION. If the condition is always true or always false,i.e. if it is predictable, the branch prediction logic in the processor will pick up the pattern. On the other hand, if the processor cant predict the condition than it may affect the performance.
when talking about your code,the optimize one i can think of is
$name = false;// i dont think u should predeclare the 'name' variable
//as it is dependent on the if condition.so if the condition fails then
//the $name will be of no use.
if (condition) {
$name = $something_else;
}
if ($name) //this condition will only be executed
// when $name is true so why predeclare $name.
{ …do something…
}

Related

PHP if statement not functioning correctly

I am trying to run an if statment then checks if a cell in database holds a certain value then it sets a variable, if it does not contain that value then it sets a different value
I have tried the following code
case "Chemistry":
$type_tarin_text = ' Exp in ';
if($user_playerdata_tab['profile_type']='Drug Runner') {
$treining_value =$sp_value*11;
} else {
$treining_value =$sp_value*10;
}
$this->AddSubValueByUserID($player_id,'PlayerData','CHEMISTRY_EXP',$treining_value);
break;
It is currently setting the $treining_value as $sp_value*11 regardless of wether profile_type is 'Drug Runner' or not.
Please use == or strict === since you're expecting a string.
You're now assigning a variable which is likely not what you are trying to do.
As others have helpfully pointed out, the issue is here:
$user_playerdata_tab['profile_type']='Drug Runner'
The single = means assignment. What you were intending to do was to test whether the two were equal.
That means using == - or, to be more strict, use === (make that your go-to equality check in the future - you'll thank us later)
Your other assignments are fine, though I would recommend a single space both sides of your = signs for readability

Why use an extra set of parenthesis when using PHP boolean test in an IF()?

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.

What is the proper way of checking a table key existence before using its value?

I want to check if $table['key'] exists before using it. What is the proper way of doing this?
I've seen a lot of different codes, but I do not know if they are all equivalent and right. Here are a few examples :
// 1
if(isset($table['key'])) { ... }
// 2
if(isset($table) and isset($table['key'])) { ... }
// 3
if(isset($table) and array_key_exists('key',$table)) { ... }
if (isset($table['key']))
Yes.
if (isset($table) and isset($table['key']))
That's redundant, there's no advantage to checking both individually.
if (isset($table) and array_key_exists('key', $table))
Yes, this is also a good method if $table['key'] may hold a null value and you're still interested in it. isset($table['key']) will return false if the value is null, even if it exists. You can distinguish between those two cases using array_key_exists.
Having said that, isset($table) is not something you should ever be doing, since you should be in control of declaring $table beforehand. In other words, it's inconceivable that $table may not exist except in error, so you shouldn't be checking for its existence. Just if (array_key_exists('key', $table)) should be enough.
The rule of thumb I personally apply:
If the value that corresponds with the key may be null:
If $table may not exist, use isset($table) && array_key_exists('key', $table).
Otherwise, use array_key_exists('key', $table).
In all other cases, use isset($table['key']).
In the cases of 1.1 and 1.2, it's technically possible that $table is not an array; in that case you would need to add is_array($table) as well ... but if it ever gets this far, something else is wrong imho.

Coding Style: function calls inside statements

Ok, first of all, i suspect this is going to be closed.
Right, i have a question relating to using function calls inside statements as opposed to assigning to a variable first.
For example:
(code is in php, but question applies generally. Also, code is overly simplified)
if (myAmazingFunction() === true) {
// do something amazing
}
instead of
$amazingresult = myAmazingFuncton();
if ($amazingResult === true) {
// do something amazing
}
The question is:
Is there any performance, or other underlying pros or cons to each approach
Stylistically, is any of the approaches considered better than the other
In most languages, there will be no performance difference. In the first case, the compiler will allocate storage for the result of the function call before checking whether it is true. In the second case you're simply making this explicit.
If you are debugging, sometimes the second form is easier, as you can set a breakpoint on the second line and check the value returned by the function before the comparison is made - but then you see the result of the function by the path the executing code takes anyway in the example you've given. You can also re-use the value without rerunning the function, as Zac says in his comment.
Stylistically, this is going to be largely subjective. The only thing I'd say here is that if your variable name makes the purpose of the function output clear, then you might be adding something to the ability for others to understand your code easily.
#DavidM's answer is correct. However, I'd just like to add that stylistically, I think it depends on the name of the function and its context.
Example:
if ($food->tastesGood()) {
echo 'Mmmm!';
}
// vs.
$foodTastesGood = $food->tastesGood();
if ($foodTastesGood) {
echo 'Mmmm!';
}
In this case, it's very clear that the return value of the method tastesGood() is going to be a boolean from both the name of the method and its context. Using a temporary variable adds nothing to your code except making it redundant and less-readable at a glance. In addition, if the variable is not defined right before its used, then you have to go find the definition to understand the condition. In these cases, I would say use of a variable is worse.
Another example:
if ($dishes->wash() !== FALSE) {
echo 'Sparkly!';
}
// vs.
$dishesAreClean = $dishes->wash() !== FALSE;
if ($dishesAreClean) {
echo 'Sparkly!';
}
In this case, we can't really infer the return type of the wash() method from its name, and indeed, it would seem that it returns nothing on success and FALSE on errors. Checking if the dishes are clean then requires us to make sure that there were no errors, but the first case doesn't make for particularly readable or self-documenting code. The second case, however, adds very explicit information about what's going on by way of the temporary variable. In these cases, I would say use of a variable is better.
Is there any performance, or other underlying pros or cons to each approach
Performance-wise, assigning an extra variable that you will use only in your if condition will use extra memory, and one useless line of code. So it will use more memory. Will it be noticeable? Probably not.
Stylistically, is any of the approaches considered bad
Using the method in your if statement is perfectly valid, and I think it's a better approach, since you can read the code and see exactly what value is being tested in the if condition. No need to look for the variable and search where it was affected.

identity conditional "===" , performance, and conversion

I've always came away from stackoverflow answers and any reading I've done that "===" is superior to "==" because uses a more strict comparison, and you do not waste resources converting value types in order to check for a match.
I may be coming at this with the wrong assumption, so I assume part of this question is, "is my assumption true?"
Secondly,
I'm dealing specifically with a situation where I'm getting data from a database in the form of a string "100".
The code I am comparing is this...
if ($this->the_user->group == 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
vs.
if ( (int) $this->the_user->group === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
or even
if (intval($this->the_user->group) === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
is any integrity (or performance) gained by manually casting or converting simply so you can use the identity ('===') comparison?
In your particular case == is the better option. As you (as can be seen in your code) have probably already found out many database functions will always return strings, even if you fetch an integer. So type strict comparison really only bloats your code.
Furthermore you are adding a potential (let's call it theoretic) security risk. E.g. (int) '100AB2' would yield 100. In your case this probably can't happen, but in others it may.
So: Don't overuse strict comparison, it's not always good. You mainly need it only in ambiguous cases, like the return value of strpos.
There is a performance difference between == and === - latter will be even twice as fast, see Equal vs identical comparison operator.
The difference, however is too small to be bothered with - unless the code is executed millions of times.
That's a really tiny optimization you're doing there. Personally, I don't think it's really worth it.
Any boost you gain from not casting the value when using === is lost when you explicitly cast the value. In your case, since the type is not important to you, you should just do == and be done with it.
My recommendation would be to keep === for when you need to check type as well - e.g. 0 evaluating to false and so on.
Any performance gains will be microscopically small, unless you're performing literally billions and trillions of these comparisons for days/months/years on-end. The strict comparison does have its uses, but it also is somewhat of anomally in PHP. PHP's a weakly typed language, and (usually) does the right thing for auto-converting/casting values to be the right thing. Most times, it's not necessary to do a strict comparison, as PHP will do the right thing.
But there are cases, such as when using strpos, where the auto-conversion will fail. strpos will return '0' if the needle you're searching is right at the start of the haystack, which would get treated as FALSE, which is wrong. The only way to handle this is via the strict comparison.
PHP has some WTF loose comparisons that return TRUE like:
array() == NULL
0 == 'Non-numeric string'
Always use strict comparison between a variable and a string
$var === 'string'

Categories