Checking if a variable is null [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
is_null($x) vs $x === null in PHP
In the following context !== null, !is_null() and isset() all produce the same result:
$foo = null;
function foo() {
if ($this->foo !== null) {
...
}
if (!is_null($this->foo)) {
...
}
if (isset($this->foo)) {
...
}
}
Which one is the quickest and which would you recommend in that context?

If you're not sure that the variable exists, use isset.
Example:
$content = (isset($_POST['content'])) ? $_POST['content'] : null;
Otherwise, use strict comparison to null.
if ($content === null) { }
(Really, I'm just pushing my opinion on your with the strict comparison. I just think it looks better than is_null, and it's probably an extremely small bit faster.)

Use isset only if the variable may not be set. I.e. if you do not know whether the variable exists at this point or not. Since you do know that it should exist at this point, don't use isset.
The difference between !== null and !is_null is negligible and mostly depends on your preference. Personally, I like !== null.

if ($this->foo !== null) {
//...
}
I prefer this condition.

According to me
if($this->foo!=""){
//...
}
this is the quickest one and produce the result quickly

Related

Is this (isset() && !empty()) function redundant? [duplicate]

This question already has answers here:
Why check both isset() and !empty()
(10 answers)
Closed 4 years ago.
<?php
function isset_n_empty($var) {
if (isset($var) && !empty($var)){
return true;
}
return false;
}
echo isset_n_empty($x ?? null);
?>
my function is supposed to do the simple if (isset() && !empty()) logic and i used $x ?? null because if it is not used it would give me this error for undefined variables as the example
E_NOTICE : type 8 -- Undefined variable: x -- at line z
is it redundant or well-optimized?
A variable that isn't set is considered empty by empty().
Therefore, if the variable is not set, it is also empty.
Your code could be shortened by using:
echo !empty($x);
I suppose that makes the answer to your question yes.
yes, the isset is redundant. if it's !empty(), then isset() always returns true.
No the function is not redundant. It tells you if your variable is set but also falsey. There's nothing wrong with it.
On the other hand it seems like something that shouldn't really require a function of it's own. Instead of:
echo isset_n_empty($x ?? null);
You can just do:
echo isset($x) && !$x;
It's less code and doesn't require a function.
I hope this will help:
function isset_not_empty($var){
if(!isset($var))
return false;
else
return (!empty($var))
}

Using the ternary operator in PHP for true returns only

Been playing around a bit with both the ternary operator and null coalesce these past few weeks and really enjoy the way that it's been able to simplify a lot of my logic, especially in places where I would previously have to stack a series of if (!empty($variable))-kinds of lines to an already annoyingly large if/else statement. Now I can just $object->attribute = $source->attribute ?? null, assuming I don't know if there will be an attribute in source or not.
Now, the question that I'm having issues with is trying to figure out how to best use this for logging. Say I've got a function like:
public static function addToQueue($field, $id)
{
if ($field ?? $id ?? null == null) {
return false;
} elseif ($field != 'name' && $field != 'id') {
return false;
} elseif (Queue::where($field, $id)->count() != 0) {
return true;
} else {
Queue::insert([$field => $id]);
return true;
}
}
Fairly straightforward; you send addToQueue() two arguments, the field and the id, and then it does three checks. Are any of them null? Then return false. Is field something other than name or id? Then return false. Is this entry already in the Queue? Then return true (since we're interested in making sure that the entry is in the queue, not whether we added it right now or not). And, finally, if the pair is not in the queue, we add it and - again - return true.
Now; so far so good; right? Doesn't seem to be an issue here, even though I see how I could probably make the logic inside of the function a little neater. The problem comes in my usage of it. Essentially, what I want to do is something like this - but with ternary operators:
if (QueueHandler::addToQueue($input->field, $input->value) == true) { $app->log->info($input->field . '/' . $input->value . ' added to queue.'; }
I want it to do something if the operation it carries out evaluates as true, but do nothing if it evaluates as false.
And yes, I know, it's called Ternary because you need three operations, but since PHP allows you to isset($variable) ?: echo 'Dude. It\'s not set...'; nowadays, I figured there should be a way to do the opposite, right?
The ?? operator is right associative (Source)
It means:
$field??$id??null == null
If $field is not set or null then that collapses to:
$id??null==null
If $id is not set or null that collapses to:
null==null
That expression will always be true since the null is swallowed by the ?? operator. This means $field??$id??null==null will never evaluate to a falsey value.
You need to be explicit if you want to force precedence:
($field??$id??null) == null
The ternary is shorthand for IF ELSE.
Even the code you mentioned isset($variable) ?: echo 'Dude. It\'s not set...'; is doing that (it will return $variable if isset is true), even though it appears you have just added the else part. So there is no "opposite" there is only IF and ELSE
For example:
$a = 'foo';
echo $a ?: 'bar'; // 'foo'
So, you current code is simple
if (QueueHandler::addToQueue($input->field, $input->value) == true) {
$app->log->info($input->field . '/' . $input->value . ' added to queue.';
}
As addToQueue returns bool, you can simplify to:
if (QueueHandler::addToQueue($input->field, $input->value)) {
$app->log->info($input->field . '/' . $input->value . ' added to queue.';
}
Now you're trying to use this:
!QueueHandler::addToQueue($input->field, $input->value) ?: $app->log->info($input->field . '/' . $input->value . ' added to queue.';
I don't think it is more readable then previous examples.
Wanna play with ternarys?
Do like it:
function addToQueue($field, $id)
{
return ($field??$id??null) == null?false:($field != 'name' && $field != 'id')?false:
(Queue::where($field, $id)->count() != 0)?true:Queue::insert([$field => $id])?true:true;
}
No one will understand, not even you. Every time you have to change it you will ask yourself why you did this way, but it will get your phpunit code coverage easier.
Now seriously, apokryfos spotted it. But you have to ask yourself what are you getting out of using ternarys.
It's really good for things like:
function getClub(){
return $this->isClubVisible()? $this->club: null;
}
And every operation that you would solve with an if/else but as you can see if you overuse it, it will get really messy and unreadable.

PHP why (null === $variable) and not ($variable === null) in comparison? [duplicate]

This question already has answers here:
Is there any benefit of using null first in PHP?
(5 answers)
Closed 8 years ago.
When reading Symfony2 code I came across this comparaison many times
if (null === $variable ) { ... }
I use
if ($variable === null ){ ... }
because I see it more readable.
Is there a wisdom behind using the first notation ?
No compile/interpretting difference at all, it's pure code style.
It's also known as Yoda Conditions.
It helps prevent accidental assignments:
if ($foo = null) { ... }
would not cause a parse error, while will
if (null = $foo) { ... }
1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10
2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd
Not only does it help prevent accidental assignments, but also avoids confusion when we do intentionally want to make an assignment when evaluating a condition.
if (null !== $article = $repository->findOneById($request->query->get('id'))) {
$title = $article->getTitle();
//....
}

PHP: what's an alternative to empty(), where string "0" is not treated as empty? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fixing the PHP empty function
In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time.
What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty?
That is, I'm just wondering if you have your own shortcut for this:
if (isset($myvariable) && $myvariable != "") ;// do something
if (isset($othervar ) && $othervar != "") ;// do something
if (isset($anothervar) && $anothervar != "") ;// do something
// and so on, and so on
I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).
This should do what you want:
function notempty($var) {
return ($var==="0"||$var);
}
Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the PHP type comparison tables for more info.
notempty("") : false
notempty(null) : false
notempty(undefined): false
notempty(array()) : false
notempty(false) : false
notempty(true) : true
notempty(1) : true
notempty(0) : false
notempty(-1) : true
notempty("1") : true
notempty("0") : true
notempty("php") : true
Basically, notempty() is the same as !empty() for all values except for "0", for which it returns true.
Edit: If you are using error_reporting(E_ALL), you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should always use E_ALL to conform to best practices. This link (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons.
See orlandu63's answer for how to have arguments passed to a custom function by reference.
function isempty(&$var) {
return empty($var) || $var === '0';
}
The key is the & operator, which passes the variable by reference, creating it if it doesn't exist.
if(isset($var) && ($var === '0' || !empty($var)))
{
}
if ((isset($var) && $var === "0") || !empty($var))
{
}
This way you will enter the if-construct if the variable is set AND is "0", OR the variable is set AND not = null ("0",null,false)
The answer to this is that it isn't possible to shorten what I already have.
Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.
function Void($var)
{
if (empty($var) === true)
{
if (($var === 0) || ($var === '0'))
{
return false;
}
return true;
}
return false;
}
If ($var != null)

Better way to check variable for null or empty string?

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. The following things are considered to be empty
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
For more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

Categories