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

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))
}

Related

What is the logic behind the isset() function in PHP? [duplicate]

This question already has answers here:
pass an argument that may not be set to a function, without throwing a notice
(3 answers)
Why check both isset() and !empty()
(10 answers)
Closed 4 years ago.
I accidentally experience this issue when I was writing code in one of my application.
$ar = [
'first' => 1,
'second' => 2,
......
];
when I tried to check that index in $array which doesn't exist
if(isset($ar['third']) && !empty($ar['third'])){
echo "Found";
}else{
echo "Not Found";
}
It worked without error as expected, but when I put this conditions in the common function and then checked
function sanitize($value){
if(isset($value) && !empty($value)){
return true;
}else{
return false;
}
}
if(sanitize($ar['third'])){
echo "Found";
}else{
echo "Not Found";
}
Above sample throws an exception undefined index error, can someone explain why this is causing the error.
$value is always set because it is declared as a function parameter so it always exists. So in this case using isset() is pointless.
function sanitize($value){ // <-- Variable is declared so it exists
// within the scope of this function
You are trying to refer to the $ar array at that the 'third' index before the isset/empty check is actually executed (as that is within the sanitise function).
PHP is therefore showing the error for the if(sanitize($ar['third'])){ line.

how to check if variable is empty in php [duplicate]

if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
$user_id = '-1';
$user_name = NULL;
$user_logged = NULL;
}
if ($user_admin == NULL) {
$user_admin = NULL;
}
Is there any shortest way to do it ?
And if i right, it should be tested with is_null?
It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?
If you want to test whether a variable is really NULL, use the identity operator:
$user_id === NULL // FALSE == NULL is true, FALSE === NULL is false
is_null($user_id)
If you want to check whether a variable is not set:
!isset($user_id)
Or if the variable is not empty, an empty string, zero, ..:
empty($user_id)
If you want to test whether a variable is not an empty string, ! will also be sufficient:
!$user_id
You can check if it's not set (or empty) in a number of ways.
if (!$var){ }
Or:
if ($var === null){ } // This checks if the variable, by type, IS null.
Or:
if (empty($var)){ }
You can check if it's declared with:
if (!isset($var)){ }
Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
<?php
$val = 0;
//evaluates to true because $var is empty
if (empty($val)) {
echo '$val is either 0, empty, or not set at all';
}
//evaluates to true because $VAR IS SET
if (isset($val)) {
echo '$val is set even though it is empty';
}
?>
empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:
if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
Please define what you mean by "empty".
The test I normally use is isset().
you can use isset() routine .
also additionaly you can refer an range of is_type () functions like
is_string(), is_float(),is_int() etc to further specificaly test
1.
if(!($user_id || $user_name || $user_logged)){
//do your stuff
}
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar["user_id"], etc.
<?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function check($var) {
if (isset($var)) {
echo 'Variable is SET'. PHP_EOL;
} elseif (empty($var)) {
echo 'Variable is empty' . PHP_EOL;
}
}
check($nothing);
check($something);
check($array);
Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following
if (!empty($var) && is_null($var))
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE
As opposed to being null which is handy here!
Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.
For example you will have to do things like isset() && strlen() where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false
The best and easiest way to check if a variable is empty in PHP is just to use the empty() function.
if empty($variable)
then
....

Checking if a variable is null [duplicate]

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

Just need to understand a PHP Syntax used to set POSTed var [duplicate]

This question already has answers here:
What is ?: in PHP 5.3? [duplicate]
(3 answers)
Closed 8 years ago.
So I'm using the following php code to set variables that are received from a POST method, but I'm interested in how it works.
$var1 = isset($_REQUEST['var1']) ? $_REQUEST['var1'] : 'default';
I understand what it does, but I don't understand the syntax.
Thanks for the help :)
? is just a short and optimised notation of doing this:
if (isset($_REQUEST["var1"])) // If the element "var1" exists in the $_REQUEST array
$var1 = $_REQUEST["var1"]; // take the value of it
else
$var1 = "default"; // if it doesn't exist, use a default value
Note that you might want to use the $_POST array instead of the $_REQUEST array.
This is a short hand IF statement and from that you are assigning a value to $var1
The syntax is :
$var = (CONDITION) ? (VALUE IF TRUE) : (VALUE IF FALSE);
You probably mean ternary operator
Syntax it's same like
if(isset($_REQUEST('var1') ) {
$var1 = ? $_REQUEST('var1')
}else {
$var1 =: 'default';
}
It's the synatx of the ternary operator. It's shorthand for if/else. Please read PHP Manaul
This is a 'ternary operator', what it says is:-
If var1 is set as a post variable then set var1 to that value, otherwise setvar1 to be the string 'default'. Using traditional syntax it would be:-
if (isset($_REQUEST('var1')) { $var1 = $_REQUEST('var1'); } else { $var1 = 'default'; }
its a short way of doing an if. if you are expecting a post variable its must better to use _POST rather than request.
the "?" says if the isset($_REQUEST) is true, then do the everything between the ? and : otherwise do everything between the : and the ;

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)

Categories