I'm running into this error when loading up my view:
ErrorException [ Notice ]: Undefined variable: errors
APPPATH\views\admin\category\add.php [ 2 ]
<h3>Add</h3>
<?php if( $errors ): ?>
<p><?=$errors?></p>
<?php endif; ?>
How is my checking not valid?
You might want to give this one a try:
isset Manual
or you can actually show the controller code in which you're failing to set the errors to the View object (probably inside of a condition).
As Kemo said you should use isset. What you are actually doing there is checking if the variable $errors has a value that evaluates to true/false. The non-existence of the variable does not equate to false and you wouldn't want it to, you want spelling mistakes etc... to throw errors rather than any variable just being considered null regardless of whether it's actually been declared. isset is specifically designed to check for the existence of the variable. As you still want to check if it also evaluates to true you should be doing:
if(isset($errors) && $errors)
An undefined variable means it does not exists. You can just wrap it inside isset() to do what you want to do:
<?php if( isset( $errors ) ): ?>
Isset is one of the few language constructs that work on unset variables without giving a warning / error. Another one is empty().
PHP is throwing an error because the error reporting includes the E_STRICT constant, which throws an exception if an undefined variable is pointed to.
Use isset() instead - It's good practice to check if your variable even exists (if there's a chance that it doesn't).
Related
In theory I know what is causing the errors my question is more if what I'm doing is acctually that wrong or if google app engine is just printing errors that are not that important.
So the code that causes the error:
$test = isValid($_GET["id"])
function isValid($var) {
return isset($var) AND $var != "";
}
Error:
Notice: Undefined index: id in /base/data/home/apps/somestuff/1.892737377923487/result.php on line 3
So the error says that the index id is undefined, which in some cases it is but I want to check if it is set and if it is not empty, because the form that sends this data sends empty strings in some of the fields so the isset() returns true but it is not valid data.
It might be worth checking out variable scoping in PHP to get a handle on why this error is coming up. There are three variables operating in the piece of code above.
In the first line, you set $test to be the returned value of the isValid() function, to which you provide the value of $_GET["id"] as an argument. When there is no $_GET[] variable provided with the name id, however, PHP throws a Notice saying exactly that - that the index is is undefined - but since this is just a notice, and your error reporting is set to tolerate notices, the script just carrys on, and assumes the value of $_GET["id"] to be empty (i.e., "" == false == 0 == null etc.).
In the isValid() function, you have a new variable defined ($var) which is local in its scope, existing only inside the function. Thus, $var will always be defined inside this function, and thus isset($var), inside the function, will always be true. Even when $_GET["id"] is empty, $var will still be defined with the empty value PHP automatically gave to it.
If you wanted to determine whether $_GET["id"] exists, you would have to use the isset() function on this variable, not a locally scoped variable which has been assigned with its value (or lack thereof). Thus, you could get rid of the notice, and have the same effect as before, by using this line of code:
$test = (isset($_GET["id"]) && !empty($_GET["id"]));
Hope this helps, I think the link below might help you out!
http://php.net/manual/en/language.variables.scope.php
There is an example in PHP Object-Oriented Solutions that seems to be flawed, if I understand is_null properly.
The sample code in the book is as follows:
if (!is_null($required) && !is_array($required)) {
throw new Exception('The names of required fields must be an array, even if only one field is required.');
}
This code is supposed to test that a var $required is not NULL and is an array. To my understanding, is_null() returns TRUE if the variable is not set or is NULL. So, does it make sense to negate is_null() in that example if you're trying to throw an exception when the variable is not set, NULL, or is not an array? The only way an exception is thrown is if (true && true) is satisfied.
FROM: http://www.php.net/manual/en/language.types.null.php
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
<?php
if(is_null($obj)){
echo 'is null';
}
While $obj is considered NULL because it hasn't been registered yet, it will still throw a Notice: undefined ...
The correct use for your if statement should first check to see if the variable exists then check to see if it is an array.
if (!isset($required) || !is_array($required)) {}
-or-
if (empty($required) || !is_array($required)) {}
The nice thing about is_array() is the fact that if $required IS NULL then it's not an array and will pass the if clause.
isset() and empty() will both ensure that the variable exists. Failure to pass either of these methods will quit the if statement and no errors will be returned.
I appreciate all the feedback, but somehow I think part of my question was not addressed. The fact that the variable is being tested with a Logical AND, means that both statements must be TRUE for the Exception in the if clause to run.
But, I don't think the use of !is_null($required) is correct. The sample code from the book was testing for a variable to contain an array with one to many values. Even if it has one value, the $required variable (for other reasons) still must be declared as an array with a single value. So, if $required hold's a value of (int) 5, an Exception should be thrown. If the $required variable is not declared/instantiated, an Exception should be thrown. If the $required variable holds NULL, an Exception should be thrown. Here is where the logic of this sample code fails. Using the online php command line that #Calimero posted, this logic fails when $required is set to NULL.
Instead of using !is_null($required) , is_null($required) without the negation should have been used since is_null returns TRUE if the value of $required is indeed NULL. So, if you negate is_null() when the $required value happens to be NULL, that part of the logical AND operation becomes FALSE, therefore the Exception never gets run at all because the logical AND operation requires both statements to be TRUE for the logic to jump into the curly braces. Which is precisely what the if clause was supposed to catch in the first place. The sample code was supposed to catch the $required variable not being set and not being of an array type.
And as I mentioned in a comment, isset() probably wasn't used because isset will return TRUE even if the $required variable is an empty string, a string with a space, an empty array, etc.
Someone please confirm I'm not talking stupid. LOL.
Take a look at this: (http://3v4l.org/QpVXq)
**Is_null**
The is_null is php construct language and can be used to test whether a variable is set to null.
$myVariable = null;
is_null($myVariable); // this returns true,because it is set to null
$myVariable = 10;
is_null($myVariable); // this returns false, cuz it is assigned to value
If the variable does not exist is_null will also return true,
but with an error notice as it is not supposed
to be used with uninitialized variables.
//returns true and also notice with (undefined variable notice)
is_null($myNewVariable);// true (undefined variable notice)
If the code is part of a function, it could be that the function allows for null values, but if the value is passed and it's not an array, then an exception must be thrown. If the code is not part of a function, it may be just demonstrating how to detect if a value is an array only if it isn't null, thus allowing null values.
i recently had to do a "test" for a job, and i got feed back saying that this statement was incorrect:
$images = $flickr->get_images(5, !empty($_GET['pg']) ? $_GET['pg'] : 1);
The "supposed" error was generated via the ternary operator on the first time the page was loaded, as there was no "?pg=1" (or whatever) passed via the query string.
The feed back said i should have used isset instead. I have looked at various posts both here (question 1960509) and blogs, but cannot find any definitive answer.
Is this really an error? How can i replicate this issue? do i need to put on E_STRICT or something in my php.ini file? Or might this be due to an older version of php?
Note: please don't tell me about how i should validate things.. i know this... it was a test to just see if i could use the flickr api calls.
This is perfectly fine. empty is not an actual function, it's a language construct. It does not issue a warning if a variable is not set (in that case the variable is considered empty, thus the 'function' returns TRUE just as you want), and additionally it checks for empty or zero values.
You could see empty as a normal isset check with an additional loose comparison to FALSE:
empty($var) === (!isset($var) || $var == FALSE)
$images = $flickr->get_images(5, (isset($_GET['pg']&&($_GET['pg']))) ? $_GET['pg'] : 1);
without isset you'll get error so combine them
I'd use
$images = $flickr->get_images(5, array_key_exists('pg', $_GET) ? $_GET['pg'] : 1);
Combine with !empty($_GET['pg']) if needed (i.e. array_key_exists('pg', $_GET) && !empty($_GET['pg'])), but array_key_exists is the intended function for this job.
I think in a situation like this isset is the correct function to use as it is checking the existence of the array element rather than checking if the value of the element has been set. As Martin notes, the best thing to do here is combine them as this will only check the value if the element exists, meaning that the error will not occur on the first page load.
Also, I think this will only give a warning if E_NOTICE is on (or perhaps E_WARNING as well)
The reason you would get an error is because the empty function is designed to check the value of an existing variable, whearas isset() is designed to tell you whether a variable has been instantiated, however because empty() is a language construct technically it doesn't throw an error or create a warning so most people don't see the difference.
From the docs:
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
isset — Determine if a variable is set and is not NULL. So "isset" is the correct function to use for checking for value is set or not.
More details :http://php.net/manual/en/function.isset.php
In a piece of code I found the following conditional statement:
if ( !defined('MY_CONSTANT') || MY_CONSTANT !== false )
and I am wondering what this may achieve that is not achieved by simply stating:
if ( MY_CONSTANT !== false )
..
is it not so, that in case MY_CONSTANT !== false then it MUST also be defined, making the first argument of the first example superfluous, or am I missing something?
If the constant may be undefined at that point, trying to access it will produce a warning on properly configured servers. You don't want those filling up your error logs, hence the defined() check.
The or conditional stops evaluating as soon as one of the conditions is true.
Since the conditions are evaluated left to right, and trying to check an undefined constant yelds an exception, you first check if it is defined, and then for its value.
If the constant is not defined, the if statement exits, and doesn't try to check the value.
Your version and the first version are not the same:
If it is not defined, the first condition of the first version will be true, and it will 'trigger'.
If it is not defined, your version will be false. (well, at least raise an error ;) )
no, because if MY_CONSTANT is not defined, PHP will give you an error message :
Notice: Use of undefined constant MY_CONSTANT
If MY_CONSTANT is not defined, PHP will do two things:
Log and/or display an error when you try to use it
Interpret MY_CONSTANT as if it were the literal string "MY_CONSTANT"
In a php page I have following code:
if($_REQUEST['c']!="") // I get error on this line itself. Why?
{
$pidis=(int)($_REQUEST['c']);
}
I keep getting Undefined index error.
On Googling I manage to understand that if a page is access without parameters (in URL) which we are trying to access we can get this error/warning. I believe that if a parameter is not defined in the URL it should just return empty instead of giving error/warning message.
I know that it is possible to suppress errors and warning by adding
error_reporting(E_ALL ^ E_NOTICE);
But I do not want to do this.
This same page work just fine on our company's web server but does not work on our clients web server.
Why is this happening?
How to solve this problem?
You are getting that error because you are attempting to compare $_REQUEST['c'] to something when $_REQUEST['c'] does not exist.
The solution is to use isset() before comparing it. This will remove the warning, since the comparison won't happen if $_REQUEST['c'] doesn't exist.
if(isset($_REQUEST['c']) && $_REQUEST['c']!="")
{
$pidis=(int)($_REQUEST['c']);
}
It is an E_NOTICE level error, and your level of error reporting will affect whether the error shows up or not. Your client's server has E_NOTICE level error reporting turned on, which is why it shows up there.
It is a good idea to always develop using E_ALL so that you can catch this kind of error before moving your code to other servers.
Another solution is to use the following:
$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : '';
You can also, if you prefer to return a value other than empty, by placing a default value within the final set of single quotes, e.g.
$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : 'Default Value';
or return a different variable type, for instance an integer:
$pidis = isset($_REQUEST['c']) ? $_REQUEST['c'] : 34;
Instead of isset() you can also use: array_key_exists().
The difference between both methods is that isset() checks also whether the value of the variable is null. If it is null then isset returns false whereas array_key_exists() returns always true if the key exists (no mater which value). E.g.:
$array = array('c' => null);
var_dump(isset($array['c']))); // isset() returns FALSE here
var_dump(array_key_exists($array['c']); //array_key_exists() returns TRUE
Depending on the context, it is important to distinguish this. In your case I don't think it matters doesn't matter, as (I guess) a request parameter never will be null (except one overwrites it manually).
Use isset($_REQUEST['c']) to test if it exists first.
PHP is giving a notice (which is not an error : it's just a notice) when you are trying to use a variable that doesn't exists, or an array element that doesn't exist.
This is just to help you, and you should not mask those notices : they are here to help you -- for instance, to help you detect typos in variable names.
Before using that array index, if it's not always present, you should test if it's here, using isset :
if (isset($_REQUEST['c']) && $_REQUEST['c']!="") {
// ...
}
Clean way could be :
$pidis = $_REQUEST['c'] ?? null
this is same as checking isset request but shorter.