I am just getting back in to PHP after many years and building a basic sit to start things off.
I have an index.php on my root and want to check for input from isset when either the value is ?home or just simply blank.
So easy enough I can start with:
if (isset($_GET['home']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/content.html.php';
}
But my issue is trying to get it to work if there is nothing to get? I can see a couple of ways to do it but I think I am missing something simple to add to the first line.
Any help appreciated.
Lee
isset() checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if variable exists otherwise returns FALSE.
On the other hand the empty() function checks if the variable has an empty value, empty string , 0, NULL ,or False. Returns FALSE if variable has a non-empty and non-zero value.
For details have a look here
http://us.php.net/manual/en/function.isset.php
http://us.php.net/manual/en/function.empty.php
Related
In various PHP tutorials I see this syntax -
if ($_POST) {
do something
}
I want to know whether this is equivalent to either isset or !(empty) (either one) or has different properties.
It attempts to evaluate the expression and cast it to boolean.
See 'Converting to boolean' at http://php.net/manual/en/language.types.boolean.php to see which values will be equivalent to true and which to false.
It does NOT however check for array key existence (i.e. isset), so if you try if ($_GET['somekey']) but somekey does not exist, you will see PHP Notice: Undefined index: somekey and then false will be assumed.
The best practice would be to perform empty() or isset() checks manually first as fits.
Good question. You are adressing one of PHPs dark sides if you ask me.
The if statement
Like in any other language I can imagine if evaluates the parameter to either true or false.
Since PHP doesn't really know types you could put any expression as parameter which will then be casted to bool as a whole
Following values are considered to be "FALSE"
boolean FALSE
integer 0
float 0.0
empty string
string "0"
any array with zero elements
NULL e.g. unset variables or $var = null
SimpleXML objects when created from empty tags
EVERY other value or expression result is casted to bool TRUE
Now, knowing this, all we need to find out is, what an expression or function returns when executed
If no POST data is set, the following expression would be TRUE
$_POST == FALSE
The isset function
isset returns bool TRUE when the given variable is set and not null.
parameters can be variables, array elements, string offsets and data members of objects.
In PHP 5.4 they fixed the behaviour with string offsets
$var = FALSE;
isset( $var ) === TRUE;
$var === FALSE;
More here
http://de1.php.net/manual/en/function.isset.php
The empty function
Returns false when a variable is considered to be empty or does not exist.
Those values are considered empty:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following values are considered to be empty:
"" (empty string)
0 (integer)
0.0 (float)
"0" (string)
NULL
FALSE
array() (empty array)
Also declared variables without value are empty
compare table
$var = FALSE;
isset($var) === TRUE;
empty($var) === TRUE;
$var === FALSE;
if ($_POST)
This will evaluate to true if there are any elements in the POST array.
if(isset($_POST))
This will always evaluate to true because the POST array is always set, but may or may not contain elements, therefore it is not equivalent to the first example.
if(!empty($_POST))
This however, is equivalent to the first example because empty() checks for contents in the array.
A good generic way of testing if the page was posted to is:
if($_SERVER['REQUEST_METHOD'] == 'POST')
$_POST:
this is used to find whether data is passed on using HTTP POST method and also extracting the variables sent through the same which are collected in an associative array
isset:
checks whether a variable is set(defined) or is NULL(undefined)
PHP.net is an invaluable source of information for figuring out the intricacies and quirks of the language.
With that said, those are not equivalent. The if statement converts the expression to a boolean value (see here for information on what is considered false).
isset is used to "determine if a variable is set and is not NULL."
empty determines whether a variable is empty, i.e., "it does not exist or if its value equals FALSE."
Best practice if you want to check the value of a variable but you aren't sure whether it is set is to do the the following:
if(isset($var) && $var) { ... }
ie check isset() AND then check the variable value itself.
The reason for this is that if you just check the variable itself, as per the example in your question, PHP will throw a warning if the variable is not set. A warning message is not a fatal error, and the message text can be suppressed, but it's generally best practice to write code in such a way that it doesn't throw any warnings.
Calling isset() will only tell you whether a variable is set; it won't tell you anything about the value of the variable, so you can't rely on it alone.
Hope that helps.
In my project, I have a wrapper class for $_SESSION, so session variables can be accessed by $session->var. I was trying to check if session variables were set or not using isset:
if (!isset($this->session->idUser)) {
...
}
but isset is not returning anything. So in my wrapper class I wrote the following function to test what was going on.
public function isItSet($var)
{
die(isset($_SESSION["id"]));
}
this results in an empty page. I tried:
public function isItSet($var)
{
die(is_null(isset($_SESSION["id"])));
}
still an empty page. Then I tried:
public function isItSet($var)
{
die(isset($_SESSION));
}
This returns 1.
Can anyone tell me why trying to check if a session variable is set returns nothing?
To support isset() you need to overload the function in your wrapper.
So, in your wrapper, add:
public function __isset($var){
return isset($_SESSION[$var]);
}
To use it, you just have to do:
isset($this->session->myVar);
If it is still not working, do:
var_dump($_SESSION)
This will dump the whole $_SESSION array and show you whether the variable you are checking for actually exists.
In my opinion, issue is related to testing and not with PHP session.
The MAIN REASON behind why session variable isset returns nothing is use of
die()
function which is equivalent to exit() according to PHP manual itself.
http://in1.php.net/die
So, use var_dump() instead.
isset returns an empty page because your variable does not exist in session, so isset return false, however, echo false return ''.
It was already written in the commentary to hakre
You can test this like that:
echo "false : " . false . "\n";
echo "true : " . true . "\n";
=>
false :
true : 1
So, for your test, do a var_dump($_SESSION) and you will see if it is normal that isset($_SESSION['id']) returns false.
You can also test: die("false : " . (false == isset($_SESSION['id'])));
Your results are basically correct.
The boolean values being pass to each function just confused you i think.
Heres a clear explainations what happens to each of your statement.
LETS GET IT ONE BY ONE
// declaring this array as a set of session being passed as sample.
$string = array('name'=>'kaii');
echo die(isset($string['id'])); // figure 1
// step
// isset($string) returns a value of false because of unexistent of an array with the name of id.
// die(false) returns nothing because of the value being passed by isset is false.
// result would be definitely empty
echo die(is_null(isset($string['id']))); // figure 2
// step
// isset($string) returns a value of false because of unexistent of an array with the name of id.
// is_null(false) returns a value of false because it only accepts NULL as its parameter value to return true.
// die(false) returns nothing because of the value being passed by is_null is false.
// result would be definitely empty
echo die(isset($string)); //figure 3
// step
// isset($string) returns a value of true because of a $string variable is set and exist.
// die(true) returns a value of 1 because of the value being passed is true which is equivalent to 1 .
// result would be definitely return a value of 1.
note: In general your statement is correct just a few justification is needed to support it.
Additional:
print_r(),var_dump()
use it to check your session if it has a name that youre trying to
declared.
A brief explanation:
isset()
returns a boolean value of true or false
is_null()
accepts only a NULL parameter value to return a boolean value of
true else it goes false.
die()
returns a value of 1 for true and empty value for false.
Reasons:
A boolean TRUE value is converted to the string "1". Boolean
FALSE is converted to ""
The isset function: Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
if the session variable is set gives TRUE if the session variable unset it gives FALSE.
Example:
$_SESSION['views']=1; session variable is setted. => gives TRUE
unset($_SESSION['views']); session variable is not setted.
=> after this if(isset($_SESSION[$var])) it gives FALSE
There are two options: the session variable is setted or not.
isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.
For More Information about isset click here
A couple of things you could try:
Add this to your codebase: http://philsturgeon.co.uk/blog/2010/09/power-dump-php-applications. It's much better than var_dump and you can clearly see true or false for boolean values. It's saved me much grief.
Second, die() doesn't always give me what I expected, so it's better to echo something and then die() right after.
As #doydoy44 mentioned, false outputs a blank, so you might be getting a blank page for good reason. Again, the link above will solve this problem and make things clearer.
Your original code above has idUser as the variable being checked, all your other examples use id. I assume you know that, but I thought I'd mention it just in case.
Finally, I'd cross-check that the session wrapper was working as I'd expected, e.g.
if (!isset($this->session->idUser)) {
dump($_SESSION);
dump($this->session);
}
I'd obviously expect to get the same content back from both of them.
Hope that helps somewhat.
By the looks of it, it seems that there is no "ID" key on the session array.
This was verified on your comment to F21's answer ("undefined index error").
What you can do is define/initialize an "ID" key on the session array with value as null or empty string "" after your session has started. Then populate it with your value later on with your codes.
This is to make sure that when you use isset($_SESSION["ID"], the result can either be true or false rather than an undefined index error.
Session variables are a bit magic. Less magic than historically, but still it's unsurprising that unusual things are observed.
It would make sense to run the tests in the question in three states: once with the session variable set, and twice without the session variable set - once with a different session variable set and once with no session variables set.
Adapting F21's answer, to support isset() you need to overload the function in your wrapper. Whilst doing that you may as well create an isset that functions as you expect.
Something along the lines of the following will solve both the 'false is invisible' and an issue with removing session values.
public function __isset($var){
if (isset($_SESSION[$var]) && $_SESSION[$var]."">"") {
return true;
} else {
return false;
}
}
I noticed this weird evaluation yesterday after searching for a few hours in my code for an error. i am passing scores into php, sometimes the score=0 which causes an issue.
send php ?blah=blah&score=0
if(!empty($_REQUEST['score']){
//do database update stuff
}else{
// show entire webpage
}
It works great unless the score=0 the if() will evaluate to false and return the entire webpage to my ajax handler and error. I have temporarily changed !empty to isset but this will cause problems in the future because isset evaluates to true even if the score key is in the url string without a value.
ex: (?blah=blah&score=&something=else)
my question is: what is the best way to recode this to work correctly now and in the future?
edit: there are a few working answers here, i appreciate everyones time. it was difficult to choose an answer
As the manual says, a variable is considered empty() if it has an empty or zero value.
So it will treat your variable wrongly as empty even though 0 is a perfectly acceptable value in your case.
If you need score to be a number, you could use isset() in combination with a is_numeric() check instead:
if((isset($_REQUEST['score']) and (is_numeric($_REQUEST['score'])){
Check out the manual page to see the kinds of values is_numeric() accepts. If score is always an integer, you can also use is_int((int)$_REQUEST['score']) but that will convert invalid input values to 0.
Additionally, as #sightofnick says, it's better to use explicit $_GET or $_POST instead of $_REQUEST.
Re your update:
In that case I would
Do check whether the variable is "0" (string "zero")
If it is "0", make it 0 (integer "zero")
If it is not 0, convert it to an integer (int)$_REQUEST["score"])
If the conversion resulted in 0, it was invalid input - exit
You have a valid integer variable.
empty() will return false if a value is zero. Use isset() or array_key_exists() instead, if you want to check if a variable in an array is set:
if (array_key_exists('score', $_REQUEST)) {...}
Try doing
if (isset($_REQUEST['score']) && ($_REQUEST['score'] !== '')) {
...
}
The isset will handle the presence/absence of the query parameter, and the strict string (!==) comparison will handle the case where the 'score' query is present but has no value. PHP treats all data coming from _GET/_POST/_REQUEST as strings, so this test is 100% reliable.
if(isset($_REQUEST['score']) && $_REQUEST['score'] != ''){
//do database update stuff
}else{
// show entire webpage
}
You may be able to solve that with
if (isset($_REQUEST['score']) && is_numeric($_REQUEST['score'])) {}
That of course if scrore can only contain numeric value
I am new to the concept of empty and null. Whilst I have endeavoured to understand the difference between them, I am more confused. I came across an article at http://www.tutorialarena.com/blog/php-isset-vs-empty.php however I still don't see when you would use isset and empty when validating forms. Seeing that I don't grasp the difference, I don't want to be using the incorrect functions as well as not be able to use the functions in other areas. Can someone give examples that will help me understand? I am very new to coding so would appreciate if someone could give me real world examples and at the same time keep it simply enough for noob to follow.
A variable is NULL if it has no value, and points to nowhere in memory.
empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL.
The following things are considered to
be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Source.
Example
$a is NULL.
$a = '' is empty, but not NULL.
Update
If $a='' is empty but not NULL, when do I use the empty() function and when do I use the isset() function.
isset() will return FALSE is the variable is pointing to NULL.
Use empty() when you understand what is empty (look at the list above).
Also when you say it points nowhere in memory, what does that mean exactly?
It means that $str = '' will be in memory as a string with length of 0.
If it were $str = NULL, it would not occupy any memory.
Null is a placeholder that generally means "no data about this is available".
The use of null for this is just a convention, but a rather widespread one, to the point where some programming languages support the convention directly. The reason this convention exists has IMHO historically to do with "pointers";
many times a procedure will be defined to return a pointer to an answer, and will return what is traditionally called a Null pointer if it could not produce an answer for some reason.
Empty means (if this is a set) that it has no members. That's an explicit answer, and it is very different than "no data about this is available".
In the PHP world, apparantly uninitialized variables have the Null value, and isset on such a variable returns FALSE.
For arrays and strings, PHP follows the convention that "empty" means "has no members" although arrays and strings are not technically sets.
PHP apparantly has this funny idea that 0 and 0.0 are also "empty", by PHP design. That's abusive of the concept of "empty" IMHO: Individual numbers are not sets, so 0 can't reasonably by "empty". THis just leads to obscure programming because it violates the principle of least surprise. I'm sure the PHP designers would are that "zero is the empty number" as some kind of vague analogy; but the if analogy is vague, why bother with it? But then PHP is full of silly ideas.
The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false).
refer this link for more https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
NULL is a special value which explicitly states that the variable has not been set to any value yet. Be careful with using the empty() function as you can't just determine that a variable is exactly NULL using it. For example the empty() function will return true if an int is set to 0. If you need to make sure a variable is exactly NULL use if($variable == NULL).
For more info on empty() see http://php.net/manual/en/function.empty.php
There are some good answers here, which I won't repeat. In the case of validating forms, though, when a form is submitted, the value of each form input element is sent to the server in the $_POST variable. You can check for the existence of a particular input by using isset().
isset($_POST['username'])
If this returns true, then this request to the server was the result of posting a form containing an input element named "username". Now that we know that we have a value for that form element, we can see if it has a valid value. empty() will tell us whether the user actually entered any data in the field, or whether they left it empty.
empty($_POST['username'])
If that returns true then the form submitted to the server had a field named "username" but the user didn't enter anything into before submitting the form.
Been awhile since i used PHP but if other languages are anything to go by empty will indicate an existing object/map/array that has no contents while null would indicate a variable that has no meaning/definition at all (uninitialised).
In database SQL, NULL means "no value".
The empty() is a nice fast way to see if the variable holds any useful info... that is for strings empty() returns true for a string of "" as well as a null string.
So you can write something like this:
if (! empty($name)) echo $name;
More info see here: PHP: empty()
isset() returns true if both these conditions are met:
The variable has been defined and has not yet been unset.
The variable has a non-null value in it.
A variable is automatically defined when it gets set to something (including null). This has a direct implication in arrays.
$a=array();
$a['randomKey']=true;
$a['nullKey']=null;
var_dump(isset($a['randomKey'])); // true
var_dump(isset($a['nullKey'])); // true, the key has been set, set to null!
var_dump(isset($a['unsetKey'])); // false !
unset($a['randomKey']);
var_dump(isset($a['randomKey'])); // false ! it's been unset!
From above, you can check if various $_POST fields have been set. For example, a page that has been posted to, stands to reason, has the submit button name in the $_POST field.
empty() on the other hand, tests if the variable holds a non zero value. This means that values that (int) cast to 0, return false too. You can use this to see if a specific $_POST field has data in it.
This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).
Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.
In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null. The second example is akin to empty.
Here is my code:
<?php
$ja = '';
if(isset($ja))
echo "cool!";
?>
I get a "cool!" when running this simple piece of code in my browser. I learned from php.net that
isset — Determine if a variable is set
and is not NULL
Well, in my code, I did declare the variable $ja, but I didn't add any value to it, so shouldn't it be "NULL"?
Even though '' seems like nothing, it still has a value (a NULL character at the end of the string).
isset() checks if the variable is set or not, which in the case (to ''), it is. You may want to set $ja to NULL first beforehand, instead of setting it to an empty string... or use empty() ;)
The empty string is still a value. so you did give it a value which is not null - '' is a perfectly normal string value. perhaps you want ! empty($ja)
Isset is used to tell whether a variable is set or not:
isset($notDefined) //false
$notDefined = 0;
isset($notDefined) //true
(Assuming that $notDefined hasn't been defined before)
To check whether the variable is empty you can use if(empty($var)) or if($var==0)
You did add value to $ja - you set it to an empty string. An empty string is not null.
What you may be confused with is that an empty string and null both evaluate to "false" in PHP when you cast it to Boolean.
PHP's documentation is fairly clear on usage of isset.
The isset function does determine whether or not an object has a value. "NULL" is truly the only way to give an object a value of nothing. $s = '' simply gives an output of nothing. BOOL values(true/false) says that it's yes or no... 0 simply gives the object a int value of 0.
As the name implies of the function, it checks if some variable has been set, in a sense not that it has some value, but in a sense that it has been created. I think the name could be a bit confusing so I will bring a javascript analogy. In javascript to check if the variable exists you do the following:
if (typeof(somevar) == "undefined")
alert("Sorry, the variable has not been set already")
else
alert("Congratulations, the variable has not been set")
So, what you are doing is that you are making a variable $ja, and since by doing so, the variable already exists and therefore has been set.
Hope this helps