strange null question - php

I want to use such code:
$arr=array('a'=>$a);
but $a is not defined, so I get error. But if I write this code before
if (!isset($a))
$a=null;
all works. Why? In the beginning $a is not defined , so $a=null. or underfined!=NULL ?

When you write
array("a"=>$a)
it means that you want the key "a" refers to a variable reference named $a which does not exist in the first place thus you are getting an error; but when you add
$a=null;
before hand, although you are setting $a to null but actually you are creating a variable reference named $a that's known by PHP so there will be no errors.

Yes, in truth undefined != null, although the difference is only in the eyes of PHP when it decides whether to throw an error or not. Otherwise it's the same thing.

As you already discovered undefined is different from null.
Undefined means that the name $a in not yet into the scope of your function/code.
$a=null is a (no)value assigned to a variable.
By the way you should get a Notice, not an error as using undefined variables as right-values php warns you about a probable typo and proceed with the script execution.
As a rule of thumb, if you address an undefined variable on the left of the assignment (=) simbol (a left-value name) then php create a new variables name and bind it into the current scope, if the reference is on the right (are you using the value contained instead than the variable itself) php warns you and keep going. You can change this behaviour by the error_reporting function.

see the manual of isset
Returns TRUE if var exists and has
value other than NULL, FALSE
otherwise.

Related

Why is a varibale "NULL" instead of being undefined?

I was expecting to see a notice like PHP Notice: Undefined variable: a, however when I run this code it works perfectly fine. Moreover, the variable becomes NULL. Why?
<?php
function($a = 1) use (&$a) {};
var_dump($a); // NULL <---- Expected a Notice "undefined", got "NULL"
Demo
i think the & operator silently create the variable if it doesn't exist already. seems this page try to explain it:
If you assign, pass, or return an undefined variable by reference, it will get created. , so when you do use (&$a) , & sees that $a doesn't already exist, and create it..
as for undefined, that's not a real type in PHP. (unlike, for example, javascript, which actually have a type called undefined, and a separate type called null)
why null? given that undefined doesn't exist, its the only logical choice for the initial value, what did you expect it to be initialized to?
"If you don't initialize your variables with a default value, the PHP will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour."

Google App Engine gives me 'Undefined index' errors, that are not there in the local enviroment

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

Assigning NULL to a variable in PHP: what does that do?

In maintaining code, I'm encountering loops, where at the end of the loop several variables are set to NULL like so: $var = NULL;. From what I understand in the manual, NULL is meant mostly as something to compare against in PHP code. Since NULL has no type and is not a string or number, outputting it makes no sense.
I unfortunately cannot provide an example, but I think the NULL values are being written to a file in our code. My question is: does $var have a value after the assignment, and will echoing/writing it produce output?
EDIT: I have read the PHP manual entry on NULL. There is no need to post this: http://php.net/manual/en/language.types.null.php in a comment or answer, or top downvote me for not having RTM. Thank you!
[ghoti#pc ~]$ php -r '$i="foo"; print "ONE\n"; var_dump($i); unset($i); print "TWO\n"; var_dump($i); $i=NULL; print "THREE\n"; var_dump($i); print "\n"; if (isset($i)) print "Set.\n"; if (is_null($i)) print "is_null\n";'
ONE
string(3) "foo"
TWO
NULL
THREE
NULL
is_null
[ghoti#pc ~]$
The result of isset() will be boolean false, but the variable is still defined. The isset() function would be better named isnotnull(). :-P
Note that is_null() will also return true for a value that has never been set.
Yay PHP.
null is pretty much just like any other value in PHP (actually, it's also a different data type than string, int, etc.).
However, there is one important difference: isset($var) checks for the var to exist and have a non-null value.
If you plan to read the variable ever again before assigning a new value, unset() is the wrong way to do but assigning null is perfectly fine:
php > $a = null;
php > if($a) echo 'x';
php > unset($a);
php > if($a) echo 'x';
Notice: Undefined variable: a in php shell code on line 1
php >
As you can see, unset() actually deletes the variable, just like it never existed, while assigning null sets it to a specific value (and creates the variable if necessary).
A useful use-case of null is in default arguments when you want to know if it was provided or not and empty strings, zero, etc. are valid, too:
function foo($bar = null) {
if($bar === null) { ... }
}
Null in PHP means a variable were no value was assigned.
http://php.net/manual/en/language.types.null.php
A variable could be set to NULL to indicate that it does not contain a value. It makes sense if at some later point in the code the variable is checked for being NULL.
A variable might be explicitly set to NULL to release memory used by it. This makes sense if the variable consumes lots of memory (see this question).
Dry run the code and you might be able to figure out the exact reason.
It appears that the purpose of the null implementation based off of the information provide is to clear the variable.
You can unset a variable in PHP by setting it to NULL or using the function unset().
unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on
what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the
local variable is destroyed. The variable in the calling environment
will retain the same value as before unset() was called.
Null is a special data type which can have only one value, which is itself. Which is to say null is not only a data type but also a keyword literal a variable of data type null is a variable that has no value assigned to it when a variable is created without a value it is automatically assigned a value of null this is so that whatever garbage was in that memory location before is cleared out otherwise the program may try to process it

Why interpreter show undefined as NULL?

Last time I'm exploring PHP pretty much and I was curious if it's possible to define variable without initializing it like in C++.
Well interpreter doesn't output an fatal eror (only a notice that variable test is undefined) if I'll run this code:
<?php
$test = (int) $test;
?>
And if I try to check it with var_dump() function i get:
int(0)
I assumed interpreter automatically cast undefined to integer. Well, ok it's pretty clever.
But when I removed code repsonsible for type casting and checked it with var_dump() function I get:
NULL
Well, ok. So when I assign undefined variable as undefined variable I get variable with NULL. I can understand interpreter do it for me on the run. But when I try something like this:
<?php
var_dump($test);
var_dump($test);
?>
I get two notices that test is not defined, but var_dump() returns NULL, not undefined. And now I don't get it. If I'll turn off notices var_dump() function will have same result with undefined variables and variables assigned to NULL. And here comes a question from topic. Why interpreter (or rather a var_dump() function) treats undefined and NULL as same ?
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.
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().
(int)$test = casting, force a value to data type (integer)
warning notices = cause by $test is never defined, and you trying to use it
var_dump($test) = I dun have a value for $test, so, I return you a null (by PHP)

Undefined index: Error in php script

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.

Categories