Can I use # instead of isset to assign or test superglobal variable ?
Use this :
$foo = intval(#$_POST['bar']);
Instead of this :
$foo = isset($_POST['bar']) ? intval($_POST['bar']) : 0;
works without generate a notice but maybe for some reasons, the use of isset is better than # ?
isset with the ternary operator would be cleaner and easier to read.
Error suppression on the other hand, has some overhead costs:
I first built a simple test that would loop a million times accessing
a variable with and without the suppression operator prepended. The
differences were small, yet noticeable. Using the suppression operator
ended up taking 40% longer to execute.
Sources:
http://seanmonstar.com/post/909029460/php-error-suppression-performance
http://www.lunawebs.com/blog/2010/06/07/another-look-at-php-error-supression-performance/
There's an alternative to using # for those of us who are tired of using isset() before pulling the value:
function iisset(&$var, $default = null) {
return isset($var) ? $var : $default;
}
There is no notice generated for passing a non-existent array index as a reference. So for your example you would use:
$foo = intval(iisset($_POST['bar'], 0));
I wish PHP had a function like this built-in. The amount of isset checks followed immediately by the retrieval of that array index is so common that without a function like this there is a ridiculous amount of extra code.
Update:
PHP 7 now has a built-in operator known as the null coalesce operator:
$foo = intval($_POST['bar'] ?? 0);
Related
This code works in PHP 7.x
$array = ['asda' => ['asdasd']];
$var = $array['asda']['asdasd'] ?? "yes!";
echo $var;
If we replace ?? with ?: as we have in older PHP version, this code will not work, for example:
$array = ['asda' => ['asdasd']];
$var = $array['asda']['asdasd'] ? $array['asda']['asdasd'] : "yes!";
echo $var;
It means, we will get an error like:
Notice</b>: Undefined index: asdasd in <b>[...][...]</b> on line
So, can we use the first example in PHP 7.x without afraid about anything strange/unexpected in behind? I mean, is it safe to use this instead, for example, array_key_exists or isset
Use isset() to test if the element exists.
$var = isset($array['asda']['asdasd']) ? $array['asda']['asdasd'] : "yes!";
The old :? conditional operator is a simple if/then/else -- it tests the truthiness of the first expression, and then returns either the second or third expression depending on this. The test expression is executed normally, so if it involves undefined variables, indexes, or properties you'll get a normal warning about it.
The new ?? null-coalescing operator, on the other hand, tests whether the first expression is defined and not NULL, not just whether it's truthy. Since it does it's own check for whether the expression is defined, it doesn't produce a warning when it's not. It's specifically intended as a replacement for the isset() conditional.
See PHP ternary operator vs null coalescing operator
I was wondering whether is another way to check if a variable coming from user input is set and not null, besides (the obvious choice) isset().
In some cases, we may not be using $_POST to get the value, but some similar custom function. isset() can not be used on the result of a function call, so an alternative way to perform the same check must be made. Now, isset() verifies two things:
Whether the value was set.
Whether the value is null. But there is some difference between assigning a variable the null value ( $variable = NULL; ) and getting a null value due to empty input fields. Or at least so I read.
So, is there a good way of checking both these requirements without using isset() ?
The equivalent of isset($var) for a function return value is func() === null.
isset basically does a !== null comparison, without throwing an error if the tested variable does not exist. This is a non-issue for function return values, since a) functions must exist (or PHP will exit with a fatal error) and b) a function always returns something, at least null. So all you really need to do is to check for null, no isset necessary.
I've written about this extensively here: The Definitive Guide To PHP's isset And empty.
Beyond this, it depends on what exactly you want to check:
test if a key was submitted via GET/POST: isset($_POST['key'])
test if there's a value and whether it's not == false: !empty($_POST['key'])
test if it's a non-empty string: isset($_POST['key']) && strlen($_POST['key'])
perhaps much more complex validations: filter_input
Here are some options...
PHP 7.4+ : null coalescing assignment operator
$variable ??= '';
PHP 7.0+ : null coalescing operator
$variable = $var ?? '';
PHP 5.3+ : ternary operator
isset($variable) ?: $var = '';
You can also use !empty() in place of isset()
the function !empty() works for both isset() and check whether the value of any string is not null, 0 or any empty string.
I usually prefer !empty() whenever I need to compare variable existence or in terms of its value.
The best way is isset but if you insist ... try empty() and strlen() Function to check wether it is empty or string lenghth is bigger than so many characters.
strlen() returns a number, length of the variable passed to it.
empty() checks if it has character in it or if it is null. with empty() you have to be becareful because some functions return 0 or false which is not considered empty.
if(!empty($var))....
OR
if(strlen($var)>2)...
I do it in most cases like this:
$v = my_func();
if (isset($v) and $v) {
...
}
I cant seem to find any discussion about this.
In JavaScript to check if something exists, and use a default if it doesn't is like this:
var myvariable = mysetting || 3
In PHP from what I understand, the same thing can be done like this:
$myvariable = $mysetting ?: 3;
Am i completely off on this? I understand the implications of not using isset() and not_empty() and all that, but if I just want to know if the variable exists and is truthy otherwise use a default - this should work I think. Does this syntax have any hidden bad things about it?
Because it doesn't work. That code will still throw a notice Notice: Undefined variable: mysetting in C:\wamp\www\x.php on line, which might be visible to the user, depending on the PHP settings. Apart from that, it will work. If notices are suppressed, then the end result is correct.
So, to get around that, you can either use isset, which isn't really a function, but a language construct, and is specifically designed to do this check:
$myvariable = isset($mysetting)? $mysetting: 3;
Or you can suppress the notice using the # operator:
$myvariable = #$mysetting ?: 3;
For this specific case, maybe it's acceptable, but in general the use of # is frowned upon by many. Personally, I would rather use a couple more characters and make it feel less 'dirty', but it's a matter of opinion.
Another reason why people may not use it, is that it's relatively new (PHP 5.3). Not everyone might know of this new syntax or be comfortable with it. They have been used to isset for years, and old habits die hard.
Those statements are not equivalent. From what I have found the javascript is equivalent to:
if (!mysetting) {
myvariable = 3;
} else {
myvariable = mysetting;
}
Whereas the equivalent PHP statement using the ternary operator would be:
$mysetting = isset($myvariable) ? $myvariable : 3;
aka:
if( isset($myvariable) ) {
$mysetting = $myvariable;
} else {
$mysetting = 3;
}
The ternary operator is essentially a shorthand for and if/else statement, and the first operand is interpreted as a logical expression.
Sorry if the title isn't clear enough, but in Javascript you can do this :
var input = null;
var fruit = input || 'default';
Just wondering if PHP supports that kind of checking, currently I'm using :
$fruit = !empty($input)?$input : 'default' ;
Which is quite good, but of course the Javascript method is more elegant.
Thanks
|| returns a boolean in PHP, so this operator cannot be used for it. Same for or.
However, you can use the binary ?: operator if you are using PHP5.3+:
$fruit = $input ?: 'default';
However, it has one great disadvantage destroying its usefulness in the single case where it would be most useful (when importing request variables):
$fruit = $_REQUEST['fruit'] ?: 'strawberry';
This would throw an E_NOTICE in your face if $_REQUEST['fruit'] didn't exist. So in this case you still need the ternary version of it with an isset or !empty check.
PHP doesn't because it returns a Boolean, not the last evaluated expression like in JavaScript or Ruby.
You can use a ternary or the new binary form that ThiefMaster mentions.
In PHP, the || operator returns a boolean, thus you will always get either true or false from it. The reason it's possible in JS is because it will return a value.
So, no, not possible.
What is the best way to define that a value does not exist in PHP, or is not sufficent for the applications needs.
$var = NULL, $var = array(), $var = FALSE?
And what is the best way to test?
isset($var), empty($var), if($var != NULL), if($var)?
Initializing variables as what they will be, e.g. NULL if a string, array() if they will be arrays, has some benefits in that they will function in the setting they are ment to without any unexpected results.
e.g. foreach($emptyArray) won't complain it just wont output anything, whereas foreach($false) will complain about the wrong variable type.
But it seams like an unnecessary hassle to have so many different ways of doing basically the same thing. eg. if(empty($var)) or if ($var == NULL)
Duplicate: Best way to test for a variable’s existence in PHP; isset() is clearly broken
Each function you named is for different purposes, and they should be used accordingly:
empty: tells if an existing variable is with a value that could be considered empty (0 for numbers, empty array for arrays, equal to NULL, etc.).
isset($var): tells if the script encountered a line before where the variable was the left side of an assignment (i.e. $var = 3;) or any other obscure methods such as extract, list or eval. This is the way to find if a variable has been set.
$var == NULL: This is tricky, since 0 == NULL. If you really want to tell if a variable is NULL, you should use triple =: $var === NULL.
if($var): same as $var == NULL.
As useful link is http://us2.php.net/manual/en/types.comparisons.php.
The way to tell if the variable is good for a piece of script you're coding will entirely depend on your code, so there's no single way of checking it.
One last piece of advice: if you expect a variable to be an array, don't wait for it to be set somewhere. Instead, initialize it beforehand, then let your code run and maybe it will get overwritten with a new array:
// Initialize the variable, so we always get an array in this variable without worrying about other code.
$var = array();
if(some_weird_condition){
$var = array(1, 2, 3);
}
// Will work every time.
foreach($var as $key => $value){
}
Another thing to remember is that since php is liberal in what it allows to evaluate to NULL or empty, it's necessary to use the identity operators (===, !== see http://php.net/operators.comparison. This is the reason why all of these comparison and equality functions exists, since you often have to differentiate between values with subtle differences.
If you are explicitly checking for NULL, always use $var === NULL
My vote goes for unset(), because non existing variables should generate an notice when used.
Testing gets a bit more complicated, because isset() wil be false if the variable is "not existings" or null. (Language designflaw if you'd ask me)
You could use array_key_exists() for valiables in $GLOBALS, $_POST etc.
For class properties there is property_exists().