Check, if array-"chain" exists [duplicate] - php

I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:
What I'm doing and think is not the best way to do:
if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something
My question is, exist any way to do this without declare the variable twice?
That is a simple case but imagine have to compare many of this $myvar variables.

Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:
$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.
Or you can use something like that:
$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $m ) {
$_GET[$m] = null;
}
Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.
Update
One other way to clean up the code would be using a function that checks if the value is set.
function getValue($key) {
if (!isset($_GET[$key])) {
return false;
}
return $_GET[$key];
}
if (getValue('myvar') == 'something') {
// Do something
}

As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:
// $_GET['myvar'] isn't set...
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
// $_GET['myvar'] is set but != 'hello'
$_GET['myvar'] = 'farewell';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
// $_GET['myvar'] is set and == 'hello'
$_GET['myvar'] = 'hello';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
Output:
goodbye!
goodbye!
hello!
Code demo on 3v4l.org
In general, the expression
$a ?? $b
is equivalent to
isset($a) ? $a : $b
Note that in the code example it is necessary to place parentheses around $_GET['myvar'] ?? '' as == has higher precedence than ?? and thus
$_GET['myvar'] ?? '' == 'hello'
would evaluate to:
$_GET['myvar'] ?? ('' == 'hello')
which would be true as long as $_GET['myvar'] was set and "truthy" (see the manual) and false otherwise (since '' == 'hello' is false).
Precedence code demo on 3v4l.org

If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:
if ((isset($variable) ? $variable : null) == $value) { }
The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.

As mellowsoon suggest, you might consider this approach:
required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $key => $default ) {
$_GET[$key] = $default ;
}
You put the default values and set the not recieved parameters to a default value :)

My question is, exist any way to do this without declare the variable twice?
No, there is no way to do this correctly without doing two checks. I hate it, too.
One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)

Thanks Mellowsoon and Pekka, I did some research here and come up with this:
Check and declare each variable as null (if is the case) before start to use (as recommended):
!isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;
*ok this one is simple but works fine, you can start to use the variable everywhere after this line
Using array to cover all cases:
$myvars = array( 'var1', 'var2', 'var3');
foreach($myvars as $key)
!isset($_GET[$key]) ? $_GET[$key] =0:0;
*after that you are free to use your variables (var1, var2, var3 ... etc),
PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);
... Better approaches are welcome :)
UPDATE:
Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.
!isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;

why not create a function for doing this, convert the variable your want to check into a real variable, ex.
function _FX($name) {
if (isset($$name)) return $$name;
else return null;
}
then you do _FX('param') == '123', just a thought

I use all time own useful function exst() which automatically declare variables.
Example -
$element1 = exst($arr["key1"]);
$val2 = exst($_POST["key2"], 'novalue');
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* #param mixed $var
* #param mixed $default
*
* #return mixed
*/
function exst( & $var, $default = "")
{
$t = "";
if ( !isset($var) || !$var ) {
if (isset($default) && $default != "") $t = $default;
}
else {
$t = $var;
}
if (is_string($t)) $t = trim($t);
return $t;
}

A solution that I have found from playing around is to do:
if($x=&$_GET["myvar"] == "something")
{
// do stuff with $x
}

<?php
function myset(&$var,$value=false){
if(isset($var)):
return $var == $value ? $value : false;
endif;
return false;
}
$array['key'] = 'foo';
var_dump(myset($array['key'],'bar')); //bool(false)
var_dump(myset($array['key'],'foo'));//string(3) "foo"
var_dump(myset($array['baz'],'bar'));//bool(false)

This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.
$allowed = ["something","nothing"];
if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}
Here is a function for checking multiple values at once.
$arrKeys = array_keys($_GET);
$allowed = ["something","nothing"];
function checkGet($arrKeys,$allowed) {
foreach($arrKeys as $key ) {
if(in_array($_GET[$key],$allowed)) {
$values[$key];
}
}
return $values;
}

Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.
I think it's ok to do this inside conditional statements like above. No harm done really.

No official reference but it worked when I tried this:
if (isset($_GET['myvar']) == 'something')

Related

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
....

how to store isset condition php to avoid repetition

my code:
if (isset($dayMarks[$res['resId']][$dDate])) {
$var=$dayMarks[$res['resId']][$dDate];
echo $var;
}
note that the isset condition is identical to the value assigned to $var, which creates a pretty ugly code.
How is it possible to assign the condition to $var without repeating it?
(in javascript, I'd write if (var=$dayMarks[$re...) )
This is a common problem in PHP where including files can create uncertainty about variables.
There are a two approaches that work well for me.
Default Assignment
With default assignment the $var variable will be given a default value when the key doesn't exist.
$var = isset($dayMarks[$res['resId']][$dDate]) ? $dayMarks[$res['resId']][$dDate] : false;
After this code can assume that $var will always contain a valid value.
Default Merger
My preferred method is to always declare a default array that contains all the required values, and their defaults. Using the False value to mark any keys that might be missing a value (assuming that key holds another value type besides boolean).
$default = array(
'date'=>false,
'name'=>'John Doe'
);
$dayMarks[$res['resId']] = array_merge($default, $dayMarks[$res['resId']]);
This will ensure that the required keys for that variable exist, and hold at least a default value.
You can now test if the date exists.
if($dayMarks[$res['resId']]['date'] !== false)
{
// has a date value
}
While this might not work exactly for your array. Since it looks like it's a table structure. There is a benefit to switching to named key/value pairs. As this allows you to easily assign default values to that array.
EDIT:
The actual question was if it was possible to reproduce the JavaScript code.
if (var=$dayMarks[$re...)
Yes, this can be done by using a helper function.
NOTE: This trick should only be used on non-boolean types.
function _isset($arr,$key)
{
return isset($arr[$key]) ? $arr[$key] : false;
}
$a = array('zzzz'=>'hello');
if(($b = _isset($a,'test')) !== false)
{
echo $b;
}
if(($c = _isset($a,'zzzz')) !== false)
{
echo $c;
}
See above code here
$isset = isset(...); //save the value
if ($isset) { .... }; // reuse the value
...
if ($isset) { ... }; // reuse it yet again
The only thing you can do is store $res['resId'][$dDate].
$var = $res['resId'][$dDate];
if( isset($dayMarks[$var]) ) {
$var = $dayMarks[$var];
echo $var;
}
If you only want to assign a variable processing simply, you can also write this as:
$var = $dayMarks[$res['resId']][$dDate]);
if (!isset($var)) unset($var);

PHP: a short cut for isset and !empty?

I wonder if there any better ideas to solve the problem below,
I have a form with a number of input fields, such as,
<input name="pg_title" type="text" value="" />
<input name="pg_subtitle" type="text" value="" />
<input name="pg_description" type="text" value="" />
<input name="pg_backdate" type="text" value="" />
etc
But sometimes don't need certain input fields above in my form, for instance, I only need the page title for my db injection,
<input name="pg_title" type="text" value="" />
etc
And I have another php page to handle the $_POST data,
$pg_title = null;
$pg_subtitle = null;
$pg_description = null;
$pg_backdate = null;
if(isset($_POST['pg_title']) && !empty($_POST['pg_title']) ) $pg_title = $_POST['pg_title'];
if(isset($_POST['pg_subtitle']) && !empty($_POST['pg_subtitle']) ) $pg_subtitle = $_POST['pg_subtitle'];
if(isset($_POST['pg_description']) && !empty($_POST['pg_description']) ) $pg_description = $_POST['pg_description'];
if(isset($_POST['pg_backdate']) && !empty($_POST['pg_backdate']) ) $pg_backdate = $_POST['pg_backdate'];
Every time I will have to check if the $_POST of a certain input field is set and not empty, otherwise its variable will be set to null, so that I won't inject an empty space into my DB.
I find the isset and !empty in the if-condition are very repetitive when I have a long list of variables to handle.
Is there any default PHP function to 'shorten' the process above? Or do I have to write a user-defined function to handle this?
Or maybe there is another way to do this?
Just some extra code in my php page that handle the $_POST data,
$sql = "
UPDATE root_pages
SET
pg_url = ?,
pg_title = ?,
pg_subtitle = ?,
pg_backdate = ?,
pg_description = ?,
...
updated_by = ?
WHERE pg_id = ?
";
$result = $connection->run_query($sql,array(
$pg_url,
$pg_title,
$pg_subtitle,
$pg_backdate,
$pg_description,
...
$pg_id
));
as you see that $pg_subtitle, $pg_backdate, $pg_description, etc always present in my query. so if I get $pg_subtitle = '' instead of $pg_subtitle = null when there is no data in it, my db record will have an empty space for that column.
isset && !empty is redundant. The empty language construct is basically shorthand for !isset($foo) || !$foo, with !empty being equivalent to isset($foo) && $foo. So you can shorten your code by leaving out the isset check.
A much simpler way is:
$values = array('pg_title' => null, 'pg_subtitle' => null, …);
$values = array_merge($values, $_POST);
// use $values['pg_title'] etc.
If you don't want your default null values to be overwritten by falsey values, e.g. '', you can do something like this:
$values = array_merge($values, array_filter($_POST));
Just be aware that '0' is falsey as well.
You can use a simple function
function post_value_or($key, $default = NULL) {
return isset($_POST[$key]) && !empty($_POST[$key]) ? $_POST[$key] : $default;
}
Then use:
$pg_title = post_value_or('pg_title');
// OR with a default
$pg_title = post_value_or('pg_title', 'No Title');
empty($var) is an abbreviation for !( isset($var) && $var ).
So !empty($_POST['...']) will be sufficient for your situation — the isset call you have currently is redundant.
User-defined function, I 'm afraid. But they come out short enough. I have one lying around somewhere if you want to take a look, but it's really trivial as you can imagine.
Update:
Here's one I found:
define('PARAM_INT', 0);
define('PARAM_STR', 1);
function get_param($name, $default = null, $type = PARAM_INT) {
$value = $default;
if (isset($_POST[$name])) {
$value = $_POST[$name];
}
else if (isset($_GET[$name])) {
$value = $_GET[$name];
}
switch($type) {
case PARAM_INT:
$value = (int)$value;
break;
case PARAM_STR:
break;
default:
// error your heart out here
}
return $value;
}
Of course now all the cool kids do it with filter_var, but the idea is the same.
+1 for array_merge() but I think that nevertheless short form for:
if (isset($_POST['some_var']) and !empty($_POST['some_var'])) $some_var = $_POST['some_var'];
else $some_var = NULL;
should be:
$some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
yes, it causes "undefined index" notice, but it checks for both existance and emptiness
EDIT: and returns NULL of course, as OP asked.
During a small research, I've found an interesting "Control Flow Function" for this case, I've never used before: NULLIF()
So you can perform this task without PHP. Just wrap all variables in it:
NULLIF('".$_REQUEST['some_var']."', '')
in your query instead of '".$_REQUEST['some_var']."'
If variable is empty or doesn't exist it will be NULLIF('', '') as far as '' == '' it will return NULL. Otherwise it will return first arg == your variable.
Consider using the available-by-default filter extension's filter_input function. You'll avoid the missing index Notice and get data sanitization at the same time.
I do not have enough rep to comment. However, the suggestion that vladkras made to use:
$some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
is not E_ALL compliant. You should be checking array keys before accessing them using either empty() or isset() as others have suggested. Especially for user input.
Also, his second suggestion to use the MySQL function "NULLIF()" as in the following manner:
NULLIF('".$_REQUEST['some_var']."', '')
is even worse. Inserting unsanitized user input directly into a SQL query is a primary vector for a SQL injection attack.
I'm always making myself unpoular with that. But the best approach is to get over the micro optimization mantra and use the syntax construct which was devised for that #.
Factually I'm lying. I'm all too often using isset() myself. (But at least I know it's not very bright.)
And for new projects I'm now using object-oriented superglobals, which combine filtering and implicit isset tests into $_POST, $_GET, $_REQUEST wrappers. $_REQUEST->ascii["title"] or $_GET["raw"] don't bring up debug messages anymore.
This function check if variable is set, is not empty, eventually if has any value.
/**
* #param var - testing variable
* #param value
* #return boolean
*/
function is(&$var, $value = null){
if(!is_null($value)){ return IsSet($var) && $var == $value; }
return IsSet($var) && !empty($var);
}
echo $_GET['id']; // this produce Warning
echo is($_GET['id'])?'1':'0'; // return false
echo $_GET['id']; // after first using function is(), will not be produce Warning!!!
is($_GET['id']); // return false
IsSet($_GET['id']); // return false
$_GET['id'] = 7;
is($_GET['id'], 7); // return true;

PHP: Check if variable exist but also if has a value equal to something

I have (or not) a variable $_GET['myvar'] coming from my query string and I want to check if this variable exists and also if the value corresponds to something inside my if statement:
What I'm doing and think is not the best way to do:
if(isset($_GET['myvar']) && $_GET['myvar'] == 'something'): do something
My question is, exist any way to do this without declare the variable twice?
That is a simple case but imagine have to compare many of this $myvar variables.
Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:
$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.
Or you can use something like that:
$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $m ) {
$_GET[$m] = null;
}
Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.
Update
One other way to clean up the code would be using a function that checks if the value is set.
function getValue($key) {
if (!isset($_GET[$key])) {
return false;
}
return $_GET[$key];
}
if (getValue('myvar') == 'something') {
// Do something
}
As of PHP7 you can use the Null Coalescing Operator ?? to avoid the double reference:
// $_GET['myvar'] isn't set...
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
// $_GET['myvar'] is set but != 'hello'
$_GET['myvar'] = 'farewell';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
// $_GET['myvar'] is set and == 'hello'
$_GET['myvar'] = 'hello';
echo ($_GET['myvar'] ?? '') == 'hello' ? "hello!\n" : "goodbye!\n";
Output:
goodbye!
goodbye!
hello!
Code demo on 3v4l.org
In general, the expression
$a ?? $b
is equivalent to
isset($a) ? $a : $b
Note that in the code example it is necessary to place parentheses around $_GET['myvar'] ?? '' as == has higher precedence than ?? and thus
$_GET['myvar'] ?? '' == 'hello'
would evaluate to:
$_GET['myvar'] ?? ('' == 'hello')
which would be true as long as $_GET['myvar'] was set and "truthy" (see the manual) and false otherwise (since '' == 'hello' is false).
Precedence code demo on 3v4l.org
If you're looking for a one-liner to check the value of a variable you're not sure is set yet, this works:
if ((isset($variable) ? $variable : null) == $value) { }
The only possible downside is that if you're testing for true/false - null will be interpreted as equal to false.
As mellowsoon suggest, you might consider this approach:
required = array('myvar' => "defaultValue1", 'foo' => "value2", 'bar' => "value3", 'baz' => "value4");
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $key => $default ) {
$_GET[$key] = $default ;
}
You put the default values and set the not recieved parameters to a default value :)
My question is, exist any way to do this without declare the variable twice?
No, there is no way to do this correctly without doing two checks. I hate it, too.
One way to work around it would be to import all relevant GET variables at one central point into an array or object of some sort (Most MVC frameworks do this automatically) and setting all properties that are needed later. (Instead of accessing request variables across the code.)
Thanks Mellowsoon and Pekka, I did some research here and come up with this:
Check and declare each variable as null (if is the case) before start to use (as recommended):
!isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;
*ok this one is simple but works fine, you can start to use the variable everywhere after this line
Using array to cover all cases:
$myvars = array( 'var1', 'var2', 'var3');
foreach($myvars as $key)
!isset($_GET[$key]) ? $_GET[$key] =0:0;
*after that you are free to use your variables (var1, var2, var3 ... etc),
PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);
... Better approaches are welcome :)
UPDATE:
Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.
!isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;
why not create a function for doing this, convert the variable your want to check into a real variable, ex.
function _FX($name) {
if (isset($$name)) return $$name;
else return null;
}
then you do _FX('param') == '123', just a thought
I use all time own useful function exst() which automatically declare variables.
Example -
$element1 = exst($arr["key1"]);
$val2 = exst($_POST["key2"], 'novalue');
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* #param mixed $var
* #param mixed $default
*
* #return mixed
*/
function exst( & $var, $default = "")
{
$t = "";
if ( !isset($var) || !$var ) {
if (isset($default) && $default != "") $t = $default;
}
else {
$t = $var;
}
if (is_string($t)) $t = trim($t);
return $t;
}
A solution that I have found from playing around is to do:
if($x=&$_GET["myvar"] == "something")
{
// do stuff with $x
}
<?php
function myset(&$var,$value=false){
if(isset($var)):
return $var == $value ? $value : false;
endif;
return false;
}
$array['key'] = 'foo';
var_dump(myset($array['key'],'bar')); //bool(false)
var_dump(myset($array['key'],'foo'));//string(3) "foo"
var_dump(myset($array['baz'],'bar'));//bool(false)
This is similar to the accepted answer, but uses in_array instead. I prefer to use empty() in this situation. I also suggest using the new shorthand array declaration which is available in PHP 5.4.0+.
$allowed = ["something","nothing"];
if(!empty($_GET['myvar']) && in_array($_GET['myvar'],$allowed)){..}
Here is a function for checking multiple values at once.
$arrKeys = array_keys($_GET);
$allowed = ["something","nothing"];
function checkGet($arrKeys,$allowed) {
foreach($arrKeys as $key ) {
if(in_array($_GET[$key],$allowed)) {
$values[$key];
}
}
return $values;
}
Well, you could get by with just if($_GET['myvar'] == 'something') since that condition presumes that the variable also exists. If it doesn't, the expression will also result in false.
I think it's ok to do this inside conditional statements like above. No harm done really.
No official reference but it worked when I tried this:
if (isset($_GET['myvar']) == 'something')

An unnset-variable default value?

alot of time in programming the value of variables are passed through url parameters,
in php;
if (isset($_GET['var'])) {$var = $_GET['var'];}
But if that does not execute, we will have an unset variable, in which may cause errors in the remaining of the code, i usually set the variable to '' or false;
else {$var = '';}
I was wondering what are the best practices, and why : )
thank you!
create a function
function get($name, $default = "") {
return isset($_GET[$name]) ? $_GET[$name] : $default;
}
I favour using the ?: ternary operator
$var = isset($_GET['var'])) ? $_GET['var'] : 0;
but you can often combine this with code to sanitize your inputs too, e.g. if you're expecting a purely numeric argument:
$var = isset($_GET['var'])) ? intval($_GET['var']) : 0;

Categories