I'm working on a truthy/falsy where I need to check 2 values, of which one may be null, the other 0. If integer vs string value same, they'd be the same.
The simplest I've been able to break it down is:
if($var1 == $var2) {// They may be the same
if((isset($var1) && !isset($var2)) || (!isset($var1) && isset($var2))) { // Is one set, and not the other?
return true; // As different as we'll allow
}
return false; // Nope they're the same
}
return true; // Definitely different
My question would be mainly, given the above code block, is there a simpler way to check if one value is set, and not the other?
EDIT: The reason I check for equality first, is that the value may pass 1 == 10 or 10 == '10', in which case, I don't need to check further, but if null == 0, this would pass and require further checking. I saw that I can pass multiple values to isset, which would work if I required both to be set or both not set, but if one is, and not the other, that's where I need to flag.
Using the null coalescing operator may come in handy...
return ($var1 ?? null) !== ($var2 ?? null);
Checks that they are not equal and at least one is defined and not null.
You are checking for equality before checking if they are set.
I'd recommend checking if they are set first.
If the PURE goal is to check if one is set and not the other, then:
return ( ( empty($var1) && ! empty($var2) ) || ( ! empty($var1) && empty($var2) );
Per comments, isset is the requirement, so this version:
return ( ( isset($var1) && ! isset($var2) ) || ( ! isset($var1) && isset($var2) );
And, props to #deceze to suggest an even simpler version:
return ( isset($var1) != isset($var2) );
Related
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
....
Current Code:
<?php
// See the AND operator; How do I simplify/shorten this line?
if( $some_variable !== 'uk' && $some_variable !== 'in' ) {
// Do something
}
?>
And:
<?php
// See the OR operator; How do I simplify/shorten this line?
if( $some_variable !== 'uk' || $some_variable !== 'in' ) {
// Do something else
}
?>
Is there a simpler (i.e. shorter) way to write the two conditions?
NOTE: Yes, they are different, and I am expecting different ways to shorten the codes.
For your first code, you can use a short alteration of the answer given by
#ShankarDamodaran using in_array():
if ( !in_array($some_variable, array('uk','in'), true ) ) {
or even shorter with [] notation available since php 5.4 as pointed out by #Forty in the comments
if ( !in_array($some_variable, ['uk','in'], true ) ) {
is the same as:
if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {
... but shorter. Especially if you compare more than just 'uk' and 'in'.
I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D
The problem with your second code is that it can easily be exchanged with just TRUE since:
if (true) {
equals
if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {
You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.
You can make use of in_array() in PHP.
$os = array("uk", "us"); // You can set multiple check conditions here
if (in_array("uk", $os)) //Founds a match !
{
echo "Got you";
}
I like the code used by Habchi in comments
if(!($some_variable === 'uk' || $another_variable === 'in')){//do}
An alternative that might make sense especially if this test is being made multiple times and you are running PHP 7+ and have installed the Set class is:
use Ds\Set;
$strings = new Set(['uk', 'in']);
if (!$strings->contains($some_variable)) {
Or on any version of PHP you can use an associative array to simulate a set:
$strings = ['uk' => 1, 'in' => 1];
if (!isset($strings[$some_variable])) {
There is additional overhead in creating the set but each test then becomes an O(1) operation. Of course the savings becomes greater the longer the list of strings being compared is.
If you're planning on building a function in the if statement, I'd also advise the use of in_array. It's a lot cleaner.
If you're attempting to assign values to variables you can use the if/else shorthand:
$variable_to_fill = $some_variable !== 'uk' ? false : true;
You need to multi value check. Try using the following code :
<?php
$illstack=array(...............);
$val=array('uk','bn','in');
if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>
You may find it more readable to reverse your logic and use an else statement with an empty if.
if($some_variable === 'uk' || $another_variable === 'in'){}
else {
// This occurs when neither of the above are true
}
Some basic regex would do the trick nicely for $some_variable !== 'uk' && $some_variable !== 'in':
if(!preg_match('/^uk|in$/', $some_variable)) {
// Do something
}
I want to keep this short. I don't know if I have the terminology correct, but I got this example from the Codeigniter handbook Vol.1.
if (count($args) > 1 || is_array($args[0]))
I've run into this problem numerous times. Depending on the datatype different tests are more appropriate. Some tests will just fail in unexpected ways.
How does one determine the most appropriate, and possibly, the most concise test?
Just to be clear I'm looking for the most effective way to test if an object/variable is ready to use, regardless of the datatype, if that's possible.
Also I don't want the solution to apply merely to lists like in the example. It should be widely applicable.
Just use empty
if(!empty($args)){
echo 'Array is set, not empty and not null';
}
use empty() bool empty ( mixed $var )
http://www.php.net/manual/en/function.empty.php
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
I've been using the following function for a while.
You can add your own test for all possible variable types.
function is_valid_var($var)
{
if ( isset( $var ) ) {
// string
if ( is_string( $var ) && strlen( $var ) == 0 ) return false;
// array
elseif ( is_array( $var ) && count( $var ) == 0 ) return false;
// unknown
else return true;
}
return false;
}
Considering that:
The isset() construct returns TRUE if a variable is set and not NULL
The is_null() function throws a warning if the variable is not set
Is there a way to test whether a variable exists, no matter it's NULL or not, without using the # operator to suppress the notice?
EDIT
Together with your first replies, I've been thinking about this and I'm getting the conclusion that inspecting get_defined_vars() is the only way to distinguish between a variable set to NULL and an unset variable. PHP seems to make little distinctions:
<?php
$exists_and_is_null = NULL;
// All these are TRUE
#var_dump(is_null($exists_and_is_null));
#var_dump(is_null($does_not_exist));
#var_dump($exists_and_is_null===NULL);
#var_dump($does_not_exist===NULL);
#var_dump(gettype($exists_and_is_null)=='NULL');
#var_dump(gettype($does_not_exist)=='NULL');
?>
$result = array_key_exists('varname', get_defined_vars());
As you already found out, you cannot :
rely on isset, as it return false for a variable that's null.
use $not_exists===null, as it'll raise a notice.
But you could be able to use a combinaison of :
get_defined_vars to get the list of existing variables, including those which are null,
and array_key_exists to find out if an entry exists in that list.
For instance :
$exists_and_null = null;
$exists_and_not_null = 10;
$defined_vars = get_defined_vars();
// true
var_dump(array_key_exists('exists_and_null', $defined_vars)
&& $defined_vars['exists_and_null']===null);
// false
var_dump(array_key_exists('exists_and_not_null', $defined_vars)
&& $defined_vars['exists_and_not_null']===null);
// false
var_dump(array_key_exists('not_exists', $defined_vars)
&& $defined_vars['not_exists']===null);
A couple of notes :
In the first case, the variable exists => there is an entry in the list returned by get_defined_vars, so the second part of the condition is evaluated
and both parts of the condition are true
In the second case, the variable exists too, but is null
which means the first part of the condition is true, but the second one is false,
so the whole expression is false.
In the third case, the variable doesn't exist,
which means the first part of the condition is false,
and the second part of the condition is not evaluated -- which means it doesn't raise a notice.
But note this is probably not that a good idea, if you care about performances : isset is a language construct, and is fast -- while calling get_defined_vars is probably much slower ^^
I would argue here that any code requiring such a comparison would have gotten its semantics wrong; NULL is an unset value in a language that has no straightforward way of distinguishing between the two.
I used a self created function to check this easily, keep in mind it will fire off a PHP warning (I only monitor E_ERROR when I develop).
function isNullOrEmpty( $arg )
{
if ( !is_array( $arg ) )
{
$arg = array( $arg );
}
foreach ( $arg as $key => $value )
{
if( $value == null || trim($value) == "" )
{
return true;
}
}
return false;
}
if (isset($var) && (is_null($var)) {
print "\$var is null";
}
This should do the trick.
In PHP, how would one check to see if a specified item (by name, I think - number would probably also work) in an array is empty?
Types of empty (from PHP Manual). The following are considered empty for any variable:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
So take the example below:
$arr = array(
'ele1' => 'test',
'ele2' => false
);
1) $arr['ele3'] is not set. So:
isset($arr['ele3']) === false && empty($arr['ele3']) === true
it is not set and empty. empty() checks for whether the variable is set and empty or not.
2) $arr['ele2'] is set, but empty. So:
isset($arr['ele2']) === true && empty($arr['ele2']) === true
1) $arr['ele1'] is set and not empty:
isset($arr['ele1']) === true && empty($arr['ele1']) === false
if you wish to check whether is it empty, simply use the empty() function.
if(empty($array['item']))
or
if(!isset($array['item']))
or
if(!array_key_exists('item', $array))
depending on what precisely you mean by "empty". See the docs for empty(), isset() and array_key_exists() as to what exactly they mean.
<?php
$myarray=array(1,5,6,5);
$anotherarray=array();
function checkEmpty($array){
return (count($array)>0)?1:0;
}
echo checkEmpty($myarray);
echo checkEmpty($anotherarray);
?>
(for checking if empty result 1 else 0);
Compactness is what I persue in my code.
i had such situation where i was getting tab it last index of array so if put things together then this might work for the most of cases
<?php
if( ctype_space($array['index']) && empty($array['index']) && !isset($array['index']) ){
echo 'array index is empty';
}else{
echo 'Not empty';
}