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.
Related
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.
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
I have a simple function which should check if the passed in parameter is an array and has values. The function works perfectly except in the event when I pass a multi-dimensional array as the property. I suspect the isset() passes but because the key may possibly not exist it gives an undefined:
<?php
$array1 = array("John","Doe");
$array2 = array();
function valid_array($array) {
if (is_array($array) && count($array) > 0) {
return true;
}
return false;
}
// Below works great:
valid_array($array1);
// If I pass the following I get the notice
// Notice: Undefined index: sample_key in ....:
valid_array($array2['sample_key']);
?>
Any ideas?
That means, there is no array item as sample_key as its key. Use isset() to verify that, don't suppress it.
if(isset($array2['sample_key']))
valid_array($array2['sample_key']);
Such cases are called Exceptions catch them and throw an error instead.
Here is a way to raise an error upon use.
function valid_array(array $array) {
// ^ Asks for a generic array to be passed
if (is_array($array) && count($array) > 0) {
return true;
}
return false;
}
The easiest way to suppress an error is by using the '#' symbol before the function is called:
Example: #my_custom_function();
This will suppress any errors your function might churn out (but it will not fix them)
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
}
I want to check if a variable called $smth is blank (I mean empty space), and I also want to check if it is set using the function I defined below:
function is_blank($var){
$var = trim($var);
if( $var == '' ){
return true;
} else {
return false;
}
}
The problem is I can't find a way to check if variable $smth is set inside is_blank() function. The following code solves my problem but uses two functions:
if( !isset($smth) || is_blank($smth) ){
// code;
}
If I use an undeclared variable as an argument for a function it says:
if( is_blank($smth) ){
//code;
}
Undefined variable: smth in D:\Www\www\project\code.php on line 41
Do you have a solution for this?
Solution
This is what I came up with:
function is_blank(&$var){
if( !isset($var) ){
return true;
} else {
if( is_string($var) && trim($var) == '' ){
return true;
} else {
return false;
}
}
}
and works like a charm. Thank you very much for the idea, NikiC.
Simply pass by reference and then do isset check:
function is_blank(&$var){
return !isset($var) || trim($var) == '';
}
Whenever you use a variable outside of empty and isset it will be checked if it was set before. So your solution with isset is correct and you cant' defer the check into the is_blank function. If you only want to check if the variable is empty, use just the empty function instead. But if you want to specifically check for an empty string after a trim operation, use isset + your is_blank function.
Use empty. It checks whether the variable is either 0, empty, or not set at all.
if(empty($smth))
{
//code;
}