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 somethi
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 :)
As of PHP7 you can use the Null Coalescing Operator ??
to avoid the double reference:
$_GET['myvar'] = 'hello';
if (($_GET['myvar'] ?? '') == 'hello') {
echo "hello!";
}
Output:
hello!
In general, the expression
$a ?? $b
is equivalent to
isset($a) ? $a : $b
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;
}
Thanks Mellowsoon and Pekka, I did some research here and come up with this:
!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
$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;
A solution that I have found from playing around is to do:
if($x=&$_GET["myvar"] == "something")
{
// do stuff with $x
}
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;
}