Function to Avoid Variable Undefined - php

I am trying to write a function to avoid getting variable undefined error. Right now, i have a code like this:
function check($str){
if(isset($str)){
$s = $str;
} else {
$s = "";
}
}
check($_GET['var']);
The get var is not set. I am getting a variable undefined error on my screen. How do i alter my function to not throw this error and just return "" if it is not set? I don't want to have to code 100 if statements to avoid getting variable undefined. Thanks.

We already have in PHP a construct to check that. It is called isset(). With it you can check whether a variable exists. If you would like to create it with some default values if it doesn't exist yet, we also have syntax for it. It's null-coalescing operator.
$_GET['var'] = $_GET['var'] ?? '';
// or since PHP 7.4
$_GET['var'] ??= '';

Although I'm not sure if it is the right way of doing it, for the sake of providing an answer you can pass the variable by reference, this allows you to get away with passing undefined variables and check if it is set inside the function..
function check(&$str){
if(!isset($str)){
$str = "not set";
}
}
check($_GET['var']);
echo $_GET['var'];

Related

Retrieve $_GET properties in a single statement

Currently, I check to see if a $_GET or $_POST property is set by using empty(). Like this:
$status = null;
if (!empty($_GET['foo'])) {
$status = $_GET['foo'];
}
I imagine there is an even more concise way of doing the same thing built into PHP, that like what I'm doing now with empty, also avoids printing the notice saying undefined index. Maybe something like this:
$status = something($_GET['foo']);
Or, maybe I should just ignore the notice and do:
$status = $_GET['foo'];
I'm not sure what the problem is as empty() does not generate a warning for undefined variables, but if you want it in one line, you can use a ternary expression:
$status = empty($_GET['foo']) ? null : $_GET['foo'];
How about this if you want just GET:
$status = isset($_GET['foo'])?$_GET['foo']:NULL;
Or this if you want just GET and POST:
$status = isset($_GET['foo'])?$_GET['foo']:(isset($_POST['foo'])?NULL);
You can always check if the key in the $_GET array exists and set the variable to null if it isn't. Will never throw a notive.
$status = array_key_exists('foo', $_GET) ? $_GET['foo'] : null;
You can suppress the warnings by using #.
$status = #$_GET['foo'];

Command to return value if variable exists?

I often find myself writing something like this:
$val = (isset($dog->owner->name)) ? $dog->owner->name : "no owner";
Because PHP throws an error if you try to evaluate a variable that does not exist, the following will not work (PHP 5.3 and above for the new shorthand ternary syntax):
$val = ($dog->owner->name) ?: "no owner";
You can achieve the above if you turn off E_USER_NOTICE reporting, which is not something I want to do.
Is there a PHP command that will return the value of a variable if it is defined?
PHP doesn't have anything like this, but you can create your own. The key is passing by reference:
function getVar(&$var, $default=null) {
if( isset($var) ) return $var;
else return $default;
}
$blah = getVar($blah, "my default value");
No there is no command to check if the variable has a value assigned without doing what you've already done. You're going to have to either perform a check or explicitly make sure your variable has a value. Add the owner's name as a parameter in the class constructor or give it a default assignment on object creation. You can also create a method that performs this task so you can reuse the code.
You can try Error control operaors #
#$val = $dog->owner->name ?: "no owner";
echo $val, "\r\n";
And you will get what you want.

Why do people set default parameters in PHP functions?

Example:
function example($x = "")
{
Do something
}
Isn't $x empty by default already? Why set it explicitly?
Isn't $x empty by default already?
If no default is specified, $x is not an empty string by default, but an undefined variable. There is a difference between "" and NULL or undefined.
However, setting the default allows you to omit the parameter when calling the function, without it throwing a warning.
<?php
function test1($x = "DEFAULT") {
echo $x;
}
function test2($x) {
echo $x;
}
// Call each without the parameter $x:
test1();
// DEFAULT
test2();
// Output:
PHP Warning: Missing argument 1 for test2(), called in /home/mjb/test.php on line 10 and defined in /home/user/test.php on line 5
PHP Notice: Undefined variable: x in /home/user/test.php on line 6
The main reason is that setting a default on the declaration makes the argument optional:
$a = example();
$b = example(5);
One reason is so when you reuse the function you dont have to explicitly set the variable. This happens a lot when a default is set to true or false. That way a function can seem to be overloaded like you can do in other oop languages. If that variable didn't contain a default value, you'd always have to set that value or your function would throw an error, however, by setting the variable to a default value you wouldn't have to necessarily set the value of the variable. Hope that helps some :)
Once of the reasons I use default values is so that I do not have to declare the variable when calling function ie:
function something(debug=false){
doing something here;
if ($debug === true){
echo 'SOMETHING';
}else{
return true;
}
}
This way you can debug something bu simply adding the variable to the function call but if you dont' add it the functions assumes it is false. This is valuable in my $_GET security function that I am using to encrypt my $_GET strings when I turn on debug the $_GET is decoded and dumped as an array inside a
<pre>print_r($_GET);</pre>
so that I can see what the values are in the $_GET but the string is still encrypted in the address bar.
Hope that helps

PHP: Notice Undefined index even using isset

i'm getting this even using 'isset':
Notice: Undefined index
it's giving the error at:
returnifisset($_COOKIE["miceusername"], ' value="', '"');
even though i am checking if the cookie isset or not. The function is:
function returnifisset($variable, $first = '', $last = ''){
if(isset($variable) and !empty($variable)){ return $first.$variable.$last; }
}
how i should modify this function to make it work and not give that error!
You are actually accessing the variable by passing it with your function, before the isset is ever called. You can't solve this problem.
You use different function names printifisset and returnifisset.
Also you can use only !empty() statement

Checking if a constant is empty

Why is this not possible?
if(!empty( _MY_CONST)){
...
But yet this is:
$my_const = _MY_CONST;
if(!empty($my_const)){
...
define( 'QUOTA_MSG' , '' ); // There is currently no message to show
$message = QUOTA_MSG;
if(!empty($message)){
echo $message;
}
I just wanted to make it a little cleaner by just referencing the constant itself.
See the manual: empty() is a language construct, not a function.
empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
So you'll have to use a variable - empty() is really what you want in the first place? It would return true when the constant's value is "0" for example.
Maybe you need to test for the existence of the constant using defined() instead?
Just letting you know that you can do
if(!empty(MY_CONST))
since PHP 5.5.
You can get along with this if for some reason you are still not using PHP 5.5.
if (defined('MY_CONST') && MY_CONST) {
echo 'OK';
}
if (!empty(constant('MY_CONST')) {
...
}
mixed constant ( string $name )
Return the value of the constant indicated by $name, or NULL if the constant is not defined
http://php.net/manual/en/function.constant.php
what about strlen?
if(strlen(MY_CONST) == 0)
If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:
define('MY_CONST', '');
if (!MY_CONST) {
echo 'MY_CONST is empty';
}

Categories