Notice: Undefined Index when checked inside function - php

Here is the function:
function is_set($var, $placeholder = null){
if(isset($var)){
return $var;
} else {
return $placeholder;
}
}
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
is_set($_POST['freq'], '');
}
It returns "Notice: Undefined index: freq in... "
While this code works well:
echo isset($_POST['freq']) ? $_POST['freq'] : '';
Why is that??

First print_r($_POST);and check variable you trying to access is available.
you are tryin g to pass $_POST['freq']) for the validation before checking whether the variable exists.
exception triggers when your execution hits is_set($_POST['freq']); without poast parameter 'freq' .
Try some thing like
if(!empty($_POST['freq'])){
is_set($_POST['freq']);
}
or pass whole $_POST to is_set function and validate variable there.

Related

How to avoid undefined index errors on a function to detect undefined indexes in PHP?

Okay, so I wrote a function to test if an array key has a value and return it, or else, return a value from the POST array, the problem is, since some of the are undefined, I get "Undefined Index error" while I'm sending the variables to see if they're defined or not.
So, what I want to know is, how to prevent this error from happening without checking if it is set before sending it to the function?
Here's some of the code I'm using:
function issetorpost($var, $post = '') {
$return = '';
if (isset($var) && !empty($var)) {
$return = $var;
}
if (isset($post) && !empty($post)) {
$return = $post;
}
return $return;
}
And it's used on input checks on form:
<input type="text" name="inp1" value="<?= issetorpost($fromdb['inp1'],$_POST['inp1']) ?>" />

Pass a variable that is not set in a PHP function

I get a lot of array from some API and I need to check weither some variable exist or not.
I have a lot of block that look like that :
if (isset($var))
$varToSet = $var;
else
$varToSet = '';
So I've decided to make a function for that. I came with that:
function setVar($var)
{
if (isset($var))
return $var;
return '';
}
But as I would expected I got the error Undefined variable, I figured out I needed to passe the argument by reference so I would get the following prototype :
function setVar(&$var);
And It was working perfectly until now, here's an example of my problem :
// works fine
$var = "test";
$varToSet = setVar($var);
// works fine
$var = "test";
$varToSet = setVar($doesNotExist);
// works fine
$var = "test";
$varToSet = setVar($doesNotExist['index']);
// doesn't work
$var = "test";
$varToSet = setVar($var['index']);
In the last example I get Illegal string offset 'index and Only variables can be passed by reference PHP errors.
I know why I got those errors, I just can't figure out how overcome this problem.
i mainly use property_exists to check if a value exist on a json object.
function getFromJson($json,$value)
{
if (property_exists(json, $value)) {
return $json->$value;
}
return null;
}
function get($var,$value = null)
{
if (is_null($value)) {
return $var;
}
if (is_object($var) && property_exists($var, $value)) {
return $json->$value;
}
if (is_array($var)) {
return $var[$value];
}
return $var;
}
The error gives you the answer. Your variable is a string. But you are trying to access an array element by using brackets [ ].
And the second is caused by invalid refference.
This is passing by reference:
$variable = 'test';
myFunction($variable);
and this is passing by value:
myFunction('test');
That's a big difference!
You can't call string as array
$varToSet = setVar($var['index']);
You can change the line to:
echo $var['index'];
and you will still have the same error/warning.
If you want to validate if array variable is set use
isset($var['index'])
but it returns value, not a refference

isset() and empty() do not seem to fix the "undefined index" notice

The company keeps their PHP errors suppressed in code, but I turned it on to see why something of mine was not working.
Now, however, I am getting hundreds of Undefined index messages that I would like to turn off so that I can find the messages from MY code.
Here is one particular block that gives many errors:
final public function getAttribute($name) {
$value = '';
if(is_array($this->attributes[$name]) === false) { // Notice: Undefined index: name
$value = trim($this->attributes[$name]);
} else {
$value = trim(implode(' ', $this->attributes[$name]));
}
return $value;
}
To eliminate these notices, I followed the post Why check both isset() and !empty() to write it like this:
final public function getAttribute($name='') {
if (!isset($name) || empty($name)) {
return '';
}
$value = '';
if(is_array($this->attributes[$name]) === false) { // Notice: Undefined index: name
$value = trim($this->attributes[$name]);
} else {
$value = trim(implode(' ', $this->attributes[$name]));
}
return $value;
}
I still get the notices, and in the same place.
How do I fix the code so that it does not create this condition?
You are not using the right variable to check against. You need to check for whether the index of the array exists.
final public function getAttribute($name='') {
if (!isset($this->attributes[$name]) || empty($this->attributes[$name])) {
return '';
}
// ...
}
try isset($this->attributes[$name]) in your second block
This will not throw undefined index:
[...]
if (isset($this->attributes[$name])) {
// The key $name is set in $this->attributes
}
else {
// The key is not set
}
if (!isset($this->attributes[$name])) {
return NULL;
}
The above code should do it.
Use empty first, because isset will throw undefined error if the index doesn't exist, and empty will never do, like:
if (empty($name) && !isset($name)) {
return '';
}
Using AND here will prevent returning if the value is already set but equals to '', o or false.
If you want to return if the value is true, some string or value, just use empty. Not need to use isset.

Create variable in PHP regardless if value is set

If I were to create this variable:
$example = $_GET['test'];
I would get this error message if $_GET['test'] is not set:
Notice: Undefined variable...
How can I create variables like this (without having to use if statements and the like) without having to see this error message?
$example = isset($_GET['test']) ? $_GET['test'] : NULL;
Typically, I do something like the following:
function get($key, $default = null) {
return isset($_GET[$key]) ? trim($_GET[$key]) : $default;
}
$example = get('test');

How to write a function that checks if a variable is defined and is a number?

In the past when I needed to check if a variable was set and also a number, I would do:
if( isset($_GET['var']) && is_numeric($_GET['var']) )
But I think that's kind of ugly, especially when I need to check a bunch of variables in the same if statement, so I made a function:
function setAndNum($var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
The problem is that when I pass an undefined variable to the function, like this (supposing the variable in the GET array is undefined):
if( setAndNum($_GET['var']) )
I get the php error:
Notice: Undefined index: ...
So the whole purpose of the function is basically defeated (or half the purpose, at least ;) ).
One thing that confuses me is how the isset() function works, and why I can pass an undefined variable to it but not to my own function?
Is it possible to make my setAndNum() function work?
Your problem is with $_GET being an array. When you pass $_GET['var'] to your function, this array value is already looked up and used as an argument to the function. Therefore you cannot effectively check the presence of 'var' in $_GET from within this function. You could rewrite it a bit to make it work for array values, something like this:
function setAndNum($key, $array)
{
if(array_key_exists($key, $array) && is_numeric($array[$key]))
return 1;
else
return 0;
}
Then call it like this:
if( setAndNum('var', $_GET) )
It's good practice to verify a key exists before using it:
if (array_key_exists($_GET, 'var')) {
// do stuff with $_GET['var']
}
function setAndNum(&$var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
Please, try using this version:
function setAndNum(&$var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
You can use the # operator to prevent error reporting:
setAndNum(#$_GET['var']);
This way, the error message of the non-existant index will not be printed, and the return value will be 0.
You could also write two functions, one that checks for an array and one that checks for normal variable
function setAndNum($var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
function setAndNumArray($array, $key)
{
if(isset($array) && isset($array[$key]) && is_numeric($array[$key]))
return 1;
else
return 0;
}
if you are using variables from GET or POST method you may do like this as these are super globals.
function setAndNum()
{
if(isset($_GET['var']) && is_numeric($_GET['var']))
return 1;
else
return 0;
}
now coming to your another query. isset checks whether a variable is s et or not like
if(isset($_POST['submit']))
{
// any code under button click
}

Categories