How to check if any variables are set? - php

checking if all are set
if(
isset($var1) &&
isset($var2) &&
isset($var3)
){}
can be re-written as
if(isset($var1,$var2,$var3)){}
but what's the syntax for if any are set?
if(
isset($var1) ||
isset($var2) ||
isset($var3)
){}
Looks ugly; is there any better way to write this?

You have to pass strings instead of the variables, but for fun:
if(compact('var1', 'var2', 'var3')) {
echo 'one or more is set';
} else {
echo 'none are set';
}

I guess one could write a simple function to use, but there's probably a cleaner way.
function anyset(...$vars){
foreach($vars as $var){
if(isset($var)){
return true;
}
}
return false;
}
if(anyset($var1,$var2,$var3)){}

Related

How do I check for 2 keywords in PHP

I want to check for my session. The code below works:
if ($_SESSION["rol"] != 'trainer') {
}
But this code doesnt work:
if ($_SESSION["rol"] != 'trainer' || 'commandant') {
}
It should check for both, because both have permission. What am I doing wrong?
Use this
if ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] != 'commandant') {
}
$role = ['trainer','commandant'];
if(!in_array($_SESSION['rol'],$role))
{
//do some stuff
}
I will probably do the following, where the isset ensures the key exists (and helps reduce warnings when the key is not available):
if (isset($_SESSION["rol"]) && ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] == 'commandant')) {
echo 'do some...';
}
array_key_exists is a nice alternative to using isset to check for keys:
if (array_key_exists('rol', $_SESSION) && ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] ==
'commandant')) {
echo 'do more...';
}
Hope that helps.
PS: #dexter solution with a in_array() will be better over time and easier to maintain.

Check for multiple null isset values

I am checking if two values are null. If both are null I want to return false, if either or both are not null, I want to return true.
My current code returns true only when both are not null but I want it to return true when either or not null.
// check if both null
if (!isset($myarray['dataone'], $myarray['datatwo']))
{
echo 'false';
);
} else {
echo 'true';
);
}
return $emptytabs;
For that you can use relational operators. AND (&&) OR (||)
By using AND (&&) operators.
if ( (!isset($myarray['dataone']) || (!isset$myarray['datatwo'] ))
{
echo 'false';
}
else
{
echo 'true';
}
By using OR ( || ) operators.
if (isset($myarray['dataone'] && isset$myarray['datatwo'])
{
echo 'false';
}
else
{
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone']) && !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if one or both are null
if ( !isset($myarray['dataone']) || !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone'], $myarray['datatwo']) )
{
echo 'false';
} else {
echo 'true';
}
return $emptytabs;
this approach you provided is totally true , but it only return true if all the provided parameters are set according to php documentations .
so your code should works correctly . except you have unwanted parentheses that should deleted
The simplest way is to use the OR (||) operator. You want to show 'true' if one thing is set OR another thing is set. Just say that with code.
if ( isset($myarray['dataone']) || isset($myarray['datatwo']) ) {
echo 'true';
} else {
echo 'false';
}
Using the AND operator adds pointless complexity by checking that both of the two things are not set in order for it to show 'false'. That's not an intuitive way to think about it, so it doesn't make sense to write the code that way.
DISCLAIMER: This answer is opinionated.

How to quickly check what variables exist from a bunch of vars?

If you have 10 variables that are sometimes set, other times unset, is there a quick way to echo the ones that exist without throwing an exception? These vars come from user input.
I would currently write it as
if ($var_1 != NULL) { echo $var_1; }
if ($var_2 != NULL) { echo $var_2; }
if ($var_3 != NULL) { echo $var_3; }
if ($var_other_1 != NULL) { echo $var_other_1 ; }
if ($var_other_2 != NULL) { echo $var_other_2 ; }
etc.. But is there a more quicker way?
compact function will help you
Check this function: http://php.net/manual/en/function.get-defined-vars.php
You can do something like this:
<?php
$vararr = get_defined_vars();
foreach ($vararr as $name => $value) {
echo "{$name}: {$value}<br>\n";
}
Here's another option using variable variables and a list of the variables you want to examine:
foreach( array("var_1", "var_2") as $var )
{
if( isset($$var) )
{
echo $$var;
}
}

Is this the proper use of an array and isset?

So I've got this code and part of it is a form, and ALL fields are absolutely required.
I just can't find clear documentation for my needs to validate everything.
would I do something like this?
$foo = $_POST['foo'];
$bar = $_POST['bar'];
$lorem = $_POST['lorem'];
$ipsum = $_POST['ipsum'];
$isSet = array($foo, $bar, $lorem, $ipsum);
if(isset($isSet)) { /* Do the stuff */ }
or is there a better way? I don't really want to do
if(isset($foo) && isset($bar) && isset($lorem)........
because i've got about 12 fields that are required
You can do:
if (isset($foo, $bar, $lorem, $ipsum)) {.....}
Saves you one step.
http://php.net/manual/en/function.isset.php
Remember that isset will return true if you have an empty string. So, technically
isset($_POST['foo'])
would return true if foo is passed in with a blank value:
foo=&bar=&...etc.
Also,
isset(array())
returns true;
If "" is not a valid value for one of those variables, you will want to do the following:
$requiredFields = array('foo', 'bar', 'lorem', 'ipsum');
$allValid = true;
foreach ($requireFields => $fieldName) {
if (isset($_POST[$fieldName]) && $_POST[$fieldName] != "") {
$allValid = $allValid && true;
} else {
$allValid = $allValid && false;
}
}
if ($allValid) {
//...success...
} else {
//...failed...
}
You essentially check that the variable was passed and also that the variable is not set to "".
Hope that helps.

What is the most succinct way to test if either of two variables are set?

What I'm doing is, if I haven't got an ID in either $_POST or $_SESSION then redirecting. Preference is given to $_POST. So I have this:
$bool = 0;
if (isset($_POST['id'])) {
$bool = 1;
} elseif (isset($_SESSION['id'])) {
$bool = 1;
}
if (!$bool) {
...//redirect
}
Is there a quicker way to write this, APART from just removing the braces?
if(!( isset($_POST['id']) || isset($_SESSION['id']) ))
redirect();
(not sure if I understand how what's given to $_POST is preference).
You could just do:
$has_id = isset($_POST['id']) || isset($_SESSION['id']);
if (!$has_id) {
// redirect
}
(I'd recommend you to give your variables more descriptive names than just $bool.)
Although if you aren't using the variable for anything else, you could just do:
if (!isset($_POST['id']) && !isset($_SESSION['id'])) {
// redirect
}
if (isset($_POST['id']) || isset($_SESSION['id'])) {
$bool = 1;
}
This will do it, simples
$bool = (isset($_POST['id']) || isset($_SESSION['id'])) ? 1 : 0; // if isset, 1
($bool == 1?header(Location: www.whatever.com):null;
Using Conditional Operator, you can achieve this in one line statement
Example:
c = (a == b) ? d : e;

Categories