Currently whenever i am trying to determine when a variable is not defined i use the code
if($variable=="")
however i have been told by people to use the function
if(empty($variable))
Reading on this, it returns false if the value is 0, and i have plenty of array values that are zero that cant be returning false. i could always add ||$variable==0) to skip this.
But all i am asking is why is this a preferred method for determining empty variables, is it efficiency or is there more to it than that?
If you need to know, use strict type comparison:
if (empty($variable) && $variable !== 0) // !== instead of !=
Generally, you should use isset() - if the variable hasn't yet been defined, it returns false:
$a = 4;
echo isset($a) ? 'a' : 'no a'; // a
echo isset($b) ? 'b' : 'not to b'; // not to b
Related
I often encounter situations like this:
function stuff()
{
$feed_data = blablabla(...);
if ($feed_data && isset($feed_data['posts'][0]['title']))
return $feed_data['posts'][0]['title'];
return false;
}
As you can see, $feed_data['posts'][0]['title'] is returned, but it's first checked with isset() to make sure it actually exists, which is not guaranteed.
If I do not include the isset() check, it can log even uglier errors about how it doesn't exist. (When things go wrong.)
Now I'm wondering if there is some way to only have to have one instance of the reference sting $feed_data['posts'][0]['title'] in my code, yet also do the check.
This is the most obvious "solution" which I've naturally tested:
$a = $feed_data['posts'][0]['title'];
if ($feed_data && isset($a))
return $a;
However, this will log the error at the first line, because you cannot assign a variable which doesn't exist!
I don't see a way around this, and it's been bothering me for a long time. I hate having duplicate code snippets like that in my code.
It seems like there ought to be a better way.
You can use a null coalescing operator:
$a = $feed_data['posts'][0]['title'] ?? false;
It checks against having a null value, if it does, return false, else return the long variable :)
Note that this was introduced with PHP 7, you can read more here
If you're specifically looking for $feed_data['posts'][0]['title'] then you don't need to check for both this value and the "parent" $feed_data array. Simply check only for this value, as one can not exist without the other.
As mentioned by treyBake you can use the ?? operator (PHP 7+) to place the value in the if statement, when the checks the value as to if the if is executed.
Combining these two points gives:
if($a = $feed_data['posts'][0]['title'] ?? false){
// Do stuff wth $a
return $a;
}
Pre PHP 7:
c'mon, update your system ;-)
NOTE: The result $a needs to be hard checked against false so that falsey values such as 0 or empty strings are not erroneously skipped (If you DO want to skip these falsey things; use empty instead of isset).
if(
($a = isset($feed_data['posts'][0]['title']) ?
$feed_data['posts'][0]['title'] : false) !== false) {
//do stuff with $a
return $a;
}
Simple question but it comes up all the time ... what is the best way to check variables in PHP. Looking for opinions / advice. In examples below assume $pricing could be not defined, correctly defined as 'price', or incorrectly defined as array(), etc..
//Method A ?
echo (!empty($pricing) && (string) $pricing == 'price' ? 'selected="true"' : '');
//Method B ?
echo (isset($pricing) && $pricing == 'price' ? 'selected="true"' : '');
// Method C ?
/// your idea ?
Method C: don't handle $pricing being undefined or of the wrong type in this expression.
By the time you reach this expression in your code, you should have already verified that the variable you're going to use exists and checked its type, and thrown an exception if it isn't what it's supposed to be, whether you do that explicitly or through a type declaration in a method.
By casting it to a string, or ignoring it if it doesn't exist, you may be covering up a potential problem that should cause an exception. If it's not a string, then something went wrong earlier in your code that you need to fix.
So just let your expression do one thing instead of multiple things.
echo $pricing == 'price' ? 'selected="true"' : '';
Then, if you see undefined variable notices in your error log, go back and fix the problem at the source (i.e. the place where $pricing was defined or should have been.)
If you're using PHP 7+, you have the null-coalesce operator (??) to compact the expression:
($pricing ?? '') === 'price' and print 'selected="true"';
Try it online at 3v4l.org.
Let's break that down:
($pricing ?? '') gracefully handles the scenario where $pricing has not been defined. If defined, this expression returns the defined value of $pricing: otherwise, it returns the empty string ''.
=== 'price' compares the now-defined value against exactly the value we are looking for. You can extend this test, of course. Like, if you had a set of defined values, you could instead use an in_array check.
and print 'selected="true"' reacts to the boolean result of the prior test, printing the desired value in the case of a match. Since outputting an empty string is equivalent to no output at all, we can simply use the and logical operator to conditionally output. Note that echo cannot be used here, as it's a language construct. Instead use print, printf, var_dump, etc.
That said, the emerging idiom for defaulting a potentially-undefined value uses the null-coalesce operator like:
$pricing = ($pricing ?? '');
I suggest defaulting in this way, versus the inline check given above, because it ensures $pricing is defined from that spot on. Said another way, don't litter your code with ($pricing ?? '') === 'price' checks: just do it once and be done with it.
As an aside, if you wanted to do multiple things on this condition, you could use an anonymous on-call:
($pricing ?? '') === 'price' and (function() {
echo 'this';
echo 'that';
})();
But I would not recommend these gymnastics.
I would write it this way:
echo (isset($pricing) && $pricing === 'price' ? 'selected="true"' : '');
This accomplishes the following:
condition evaluates to false if $pricing is undefined
condition evaluates to false if $pricing is not the same as 'price'
Finally, you are comparing with a specific value, anything other than that value will equate to false anyway, so checking for !empty() is redundant in this case.
Be sure to use the strict ( === ) comparison though, as if("some string" == 0) will return `true ( source ).
EDIT: Also, if you are unsure whether or not the variable has been defined (for example when working with $_POST), using isset() will save you a lot of trouble.
So my code in the past needed a variable to run through 2 functions and then return the value as such.
function 1($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
// pass the return to next function
function 2($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
On the next check it returns a message to the user as such:
if($variable == -1) // display message
if($variable == -2) // display message
if($variable == true) // display message
Now, per requirement of work the variable must go through a 3rd function check still returning a -1, -2 or true and then go onto the final if statements for display.
Now this is where it gets odd. If I keep it at 2 functions the if statements work, however if I run it through the 3rd check function I need to format my if's like this in order to correctly check the return:
if($variable === -1) // display message
if($variable === -2) // display message
if($variable === true) // display message
Notice I have to add the 3rd '=' symbol. I just can't figure out why this is happening. Is this normal by some PHP law I don't know about or is this a bug?
This is not odd behavior, it's very natural for PHP.
Following expression:
if ($variable == true) {
}
means that PHP will cast left operand to less pretensive type(in this case BOOLEAN) and do comparison after this. Which obviously will result in TRUE if $variable value is not 0 or FALSE or NULL or ''
In second case i.e. === there is strict check value and type of both operands are compared.
The triple equals sign (===) only returns true if the two objects being compared are identical (of the same type and value), not just equal.
For example:
$a = 1;
$b = "1";
echo $a == $b; // True
echo $a === $b; // False
Your code does not show how you call the functions and store returns, there may be a problem. Plus, I suppose you called function 1 and 2 only for illustration because as you know you cant start name of the function with a number.
=== is 'equals exactly' (value and type). Often used for logical tests, because sometimes you need to distinguish 0 from false and 1 from true.
Essentially, I'd love to be able to define a variable as one thing unless that thing doesn't exist. I swear that somewhere I saw a shorthand conditional that looked something like this:
$var=$_GET["var"] || "default";
But I can't find any documentation to do this right, and honestly it might have been JS or ASP or something where I saw it.
I understand that all that should be happening in the above code is just to check if either statement returns true. But I thought I saw someone do something that essentially defined a default if the first failed. Is this something anyone knows about and can help me? Am I crazy? It just seems redundant to say:
$var=($_GET["var"]) ? $_GET["var"] : "default";
or especially redundant to say:
if ($_GET["var"]) { $var=$_GET["var"]; } else { $var="default"; }
Thoughts?
Matthew has already mentioned the only way to do it in PHP 5.3. Note that you can also chain them:
$a = false ?: false ?: 'A'; // 'A'
This is not the same as:
$a = false || false || 'A'; // true
The reason why is that PHP is like most traditional languages in this aspect. The logical OR always returns true or false. However, in JavaScript, the final expression is used. (In a series of ORs, it will be the first non-false one.)
var a = false || 'A' || false; // 'A'
var b = true && 'A' && 'B'; // 'B';
In such cases you should be checking for existence of the variable in $_GET and then whether it's valid for your parameters. For example:
$var = (isset($_GET["var"]) && $_GET['var'] !== '') ? $_GET["var"] : "default";
However, this can become pretty unreadable pretty quickly. I'd say keep it readable by first initializing your variable to a safe default, and then overwriting that with an external one, if that's valid:
$var = "default";
if (isset($_GET['var') && $_GET['var'] !== '') {
$var = $_GET['var] ;
}
As for your first example, $var=$_GET["var"] || "default"; exists in Javascript: var someVar = incomingVar || "default";
I've always used empty.
$var = !empty($_GET['var'])?$_GET['var']:'default';
This below does not seem to work how I would expect it, event though $_GET['friendid'] = 55 it is returning NULL
<?PHP
$_GET['friendid'] = 55;
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
echo $friendid;
exit;
?>
As of PHP 7's release, you can use the null-coalescing operator (double "?") for this:
$var = $array["key"] ?? "default-value";
// which is synonymous to:
$var = isset($array["key"]) ? $array["key"] : "default-value";
In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).
$var = $value ?: "default-value";
// which is synonymous to:
$var = $value ? $value : "default-value";
Remove the !. You don't want to negate the expression.
$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
If you're lazy and risky, you can use error control operator # and short form of ternary operator.
$friendid = #$_GET['friendid']?: 'empty';
Currently you're working with the ternary operator:
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
Break it down to an if-else statement and it looks like this:
if(!isset($_GET['friendid']))
$friendid = $_GET['friendid'];
else
$friendid = 'empty';
Look at what's really happening in the if statement:
!isset($_GET['friendid'])
Note the exclamation mark (!) in front of the isset function. It's another way to say, "the opposite of". What you're doing here is checking that there is no value already set in $_GET['friendid']. And if so, $friendid should take on that value.
But really, it would break since $_GET['friendid'] doesn't even exist. And you can't take the value of something that isn't there.
Taking it from the start, you have set a value for $_GET['friendid'], so that first if condition is now false and passes it on to the else option.
In this case, set the value of the $friendid variable to empty.
What you want is to remove the exclamation and then the value of $friendid will take on the value of $_GET['friendid'] if it has been previously set.
The best solution for this question, i.e. if you also need to 'check for the empty string', is empty().
$friendid = empty($_GET['friendid']) ? 'empty' : $_GET['friendid'];
empty() not only checks whether the variable is set, but additionally returns false if it is fed anything that could be considered 'empty', such as an empty string, empty array, the integer 0, boolean false, ...
I am using Null coalescing operator operator in if condition like this
if($myArr['user'] ?? false){
Which is equivalent to
if(isset($myArr['user']) && $myArr['user']){
From your reply to Philippe I think you need to have a look at the differences between empty and isset.
To summarise, isset() will return boolean TRUE if the variable exists. Hence, if you were to do
$fid = $_GET['friendid'] = "";
$exists = isset($fid);
$exists will be TRUE as $_GET['friendid'] exists. If this is not what you want I suggest you look into empty. Empty will return TRUE on the empty string (""), which seems to be what you are expecting. If you do use empty, please refer to the documentation I linked to, there are other cases where empty will return true where you may not expect it, these cases are explicitly documented at the above link.
if friendid is NOT set, friendid = friendid otherwise friendid = empty
Okay, I may have been having a similar issue not being familiar with the ! situation as jasondavis had.
Kind of confusing but finding out not having the ! as in... isset($avar) compared to !isset($avar) can make quite the difference.
So with the ! in place, is more stating a YES as in
since $_GET['friendid'] = 55; has been initialized...
tell me 'no' - the opposite - that it hasn't and set it to empty.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
where not having the ! tells me yes it has something in it, leave it be.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
Was far less confusing with if A$="" then.... work it. ( or if $A="" for those of PHP ).
I find this use of strings and variables all as strings to be very daunting at times. Even through the confusion, I can actually understand why... just makes things a tad difficult to grasp for me.
For me, if I need to know BOTH are true
key is set
value is truthy
and if not, use another result:
the shortest way is
$result = ($arr['b'] ?? 0) ?: $arr['a'];
(ie. if b is_set AND has a real value, use it. Otherwise use a)
So in this scenario:
$arr = ['a' => 'aaa', 'b' => 'bbb'];
$result = 'aaa'