Why should i use isset? [duplicate] - php

This question already has answers here:
Weak typing in PHP: why use isset at all?
(9 answers)
Closed 7 years ago.
I'm beginner in PHP and was wondering what's the difference between this
$variable = "text";
if($variable){
echo $variable;
}
and this
$variable = "text";
if(isset($variable)){
echo $variable;
}

Sometimes you want to know if a variable is set or not e.g. for security reasons of for debugging reasons.
The function isset() is used to determine if a variable is set and is not NULL and is accordingly returning true or false.
The expression if($variable) {} instead will evaluate to false if $variable is set but is zero or if $variable is set but its current value is false (=counterexample)
Assume:
isset($variable): Evaluates to true if a variable is set and not null
if($variable): Evaluates to true depending on the value of a variable or the result/value of an expression

The most important feature of functions like isset(), empty(), etc. to me is, that they do not throw errors when a variable is not set, like Marc B already mentioned.
PS: I strongly recommend to turn on strict mode and all error reporting during development.

isset is used to check whether input you receive contains what you expect - this is a very, very loose definition and I wrote that trying to explain easily when you'd use it.
When you set a variable yourself, then it doesn't make sense to use isset, you know it's set and that it contains some value.
However, many languages, not just PHP, deal with user input. User in this case could be a human, another computer service etc. You usually store that input inside a variable. A great example is PHP's $_POST, $_GET, $_SERVER, $_SESSION.
When you receive an input that user made via HTML form, you want to check whether certain values have been populated - in that case, you use isset.
An example HTML form:
<form method="POST" action="your_file.php">
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<button type="submit">Send</button>
</form>
Someone can submit that form, they can fill in both inputs. Or only one of them, or even none. You don't know what they've done, but regardless - PHP will provide you with a variable that might contain correct input.
If I submitted that form with nothing filled in, and if you tried to access a value for first_name - you would get a PHP warning - and you don't want PHP warnings.
Therefore, before working with user input (in this case with a $_POST superglobal array), you would check whether I filled in everything properly and you'd do that with:
if(isset($_POST['first_name']) && isset($_POST['last_name']))
{
echo "Form was filled in correctly";
}
else
{
echo "Form wasn't filled in correctly! Please fill in both fields";
}
Hopefully that clears it up a bit. Just once more, I used very trivial but real-world examples.

Perhaps you example is a bit skewed. However. if you were to ignore the first line of each code segment, perhaps you will see this differently. Consider the code segments
if($variable){
echo $variable;
}
If $variable has not been initialised and assigned a value, then the is statement will result in an error.
On the other hand, if you initialise the variable
$variable = "text";
if($variable){
echo $variable;
}
will test is the variable is true, or non zero.
The isset() function will ignore the value, and tell you if the variable is initialised.
In the following code segment, the if() statement will return true.
$variable = "text";
if(isset($variable)){
echo $variable;
}
while, in this code
<?php
if(isset($variable)){
echo $variable;
}
the if() statement will return false.

Related

PHP If Statement if (!$_POST) - What does !$_POST mean?

PHP If Statement if (!$_POST) - What does !$_POST mean?
For instance, in some legacy code I'm looking at, the code reads:
<form action="paypalorders.php" method="POST">
<input type="hidden" name="orderList" value="' . $orderList . '">
<input type="submit" value="Archive">
</form>';
if (!$_POST) {
file_put_contents('/orders.txt', $output_line1);
}
I've looked at a bunch of other threads and haven't seen this exact question asked, so I'm trying to find out what it is. I've seen threads that format it like this:
if(!empty($_POST)) {
But not quite the same as what I'm looking for. Is it the same thing, just shorthand? I'm not sure, which is why I'm asking. I've Googled around and looked at a handful of threads and I'm still not sure.
Thank you.
The ! (not) logical operator returns true if the argument on its right-hand side is not true. It forces the argument to be evaluated as a boolean. In this case, when the $_POST array is evaluated as a boolean it will evaluate as true if it is not empty and false if it is. (See converting to boolean.)
if (!$_POST) { should be a safe way to detect whether or not anything is in $_POST if you want to do that. empty isn't necessary in that case because superglobals are always set, and since you aren't referring to a specific key, you don't need to worry about an undefined index notice.
I think it's also worth mentioning that if the only point of the check is to see what type of request was sent, it is probably better to just check the request method directly, because !$_POST does not mean the request wasn't a post, since a post request can be empty.
Since $_POST is an array, if it's empty his value is null, so if(!$_POST) would look like this:
if(!null){
//code
}
The following code returns true or false, but the objective of both is the same.
if(!empty($_POST)){
//code
}
Hope it helps you!
(bool)$array evaluates to true if $array contains elements, and false if it is empty.
Since $_POST is an array, !$_POST returns true if $_POST is empty.
Another way to interpret this, you are performing conditional tasks for the case where this page was not reached through a HTTP POST method.
when you cast an array to bool, it will be cast to bool(false) if the array is empty (eg if count($arr)===0), or bool(true) otherwise. ! casts whatever it's checking to bool. because $_POST always exists, if (!$_POST) { and if(empty($_POST)) { both do the exact same thing, they check if $_POST is empty. it's not even about being legacy code, this is still perfectly valid for 7.3.0. the difference between the 2 approaches will only become apparent when you're checking variables that may not exist, !$arr will trow an Notice: Undefined variable-error if $arr doesn't exist, empty($arr) will not.

Why do i need to almost use Isset?

Why every time I need to almost use isset() I couldn't understand why the php always has notice and warnings following is the two codes and I don't understand why we need to isset().
Please explain briefly because I'm a low thinker as you can see I declare the variable x but the PHP said undefined this is only in checkbox and radio button didn't encounter in textbox and even in declaring variable we need to declare it at the top like this $var='';
Please explain my mind is in confusion right now I don't know what is true or false I know isset is use to check if the variable is set or null but why it is important. Why in checkbox it doesn't give me error HERE IS THE ERROR WITHOUT ISSET()
WRONG CODE
<?php
if(isset($_POST['Submit'])){
$x=$_POST['burger'];
if($x == ''){
echo 'Please fill it up';
}else{
foreach($x as $z){
echo $z.'<br>';
}
}
}
?>
RIGHT ONE
<?php
if(isset($_POST['Submit'])){
if(isset($_POST['burger'])){
$x=$_POST['burger'];
}
if(empty($x)){
echo 'Please fill it up';
}else{
foreach($x as $z){
echo $z.'<br>';
}
}
}
?>
Php isset() is used to check whether a variable is set or not. So without isset check, $x is not defined which results in error.(uninitialized variable $x).
Explanations below,
if(isset($_POST['Submit'])){ //checks if $_POST["submit"] is set, preventing $_POST uninitialized errors
if(isset($_POST['burger'])){ //checks if $_POST["burger"] is set, preventing $_POST uninitialized errors
$x=$_POST['burger']; //$x will be always set, bcoz its inside isset($_POST["burger"])
}
if(empty($x)){
echo 'Please fill it up';
}else{
foreach($x as $z){
echo $z.'<br>';
}
}
}
When you try to access a variable in PHP which wasn't initalized before, there will be a warning issued. So isset() is used to check if the variable exists or not.
But there is a problem with your solution, because in case when $_POST['Burger'] isn't set, $x will also not be set, it will be better to use if(isset($x)){ instead of if(empty($x)){
$_POST is an array. Normally, when you try to access a key of an array that doesn't exist, you get an error. isset allows you to check if the key exists. That way you can write an if that throws a human readable error or uses a default value in case the posted value doesn't exist.
In alternative to isset, you could use:
if (array_key_exists('Submit', $_POST)) {
}
isset is more a generic way to perform the check, and it's often used for this goal. But it has some side effects too! It can for instance return false, even if the key technically exists.
By using a specific function like array_key_exists, your code is a bit more verbose and more specific, making it easier to understand what is going on, and you won't have those forementioned side effects.

Php: about echoing a null variable

I'm currently learning php using Murach (the book, published in 2010). One of the exercises has these statements:
<label>Investment Amount:</label> <input type="text" name="investment"
value="<?php echo $investment; ?>"/><br />
<label>Yearly Interest Rate:</label> <input type="text" name="interest_rate"
value="<?php echo $interest_rate; ?>"/><br />
<label>Number of Years:</label> <input type="text" name="years"
value="<?php echo $years; ?>"/><br />
The whole gist is that the value attributes above with the echo statements have variables which have not been assigned any value at first, so the textbox is supposed to be empty according to the book. But later on the exercise this same page will be called again and the variables will now have values, thus they will be printed on the textbox. Here's the book's explanation:
These echo statements display the variables that contain the data that
the user has previously entered into the form. The first time this
page is displayed, though, these variables won’t contain data so the
text boxes will be empty.
However, upon running the program for the first time, the textboxes are in fact not empty:
Since this book was published 5 years ago I'm guessing either they worked then but do not now, or the code itself is wrong. Can anyone tell me if this is just obsolete code or is it really broken to begin with? And how can I fix it to get the desired effect of an empty textbox using a null variable?
Thanks!
You should check if they are defined.
i.e.
<?php echo (isset($years)) ? $years : ''; ?>
Also, if you turn off display_errors in your php.ini this won't happen, however this would be an ill-advised solution
The most important way of programming is programming in such a way, that someone else can also understand it. So in that case, if you plan to use this variable, declare and comment it before:
$investment = ''; // Future post investement variable, on startup empty
$interest_rate = ''; // Future interest_rate variable, on startup empty
$years = ''; // Future years variable, on startup empty
In that case everyone is sure what each variable is, and what it will contain. And no undefined error will occur.
Also notice that turning off warning display, as mentioned in comments and answers, isnt a good idea. When you write nice code, no warnings should be displayed. And turning them off is of course not a solution.
The only MUST do is to turn off warnings and errors on production, to not give hackers any possible clue, even if something goes wrong. And save them in some sort of error logger.
If you plan to use this variable with post, I suggest doing something like that:
$investement = (isset($_POST['investment'])) ? safety($_POST['investment']) : '';
Where safety is your own safety check function (remove special characters, and prevent mysql injection if you plan to echo / store data). It is the same as writing:
if (isset($_POST['investment'])) {
$investement = safety($_POST['investment']);
}
else {
$investement = ''; // init value
}
A Notice is what it is, a notice, it doesn't prevent your code from executing as such. Of course if the variable / code generating the notice is used elsewhere you can run into trouble.
So, the book is somewhat right, but I would say that it's bad practice since that you should always aim to have 0 warnings / notices, which means that you should do as #Swifty mentioned and check whether the variable is set.

I'm confused about the flow of $_POST[] variables and regular variables

I have a simple form I created, and in it I have the following checkbox:
<input type="checkbox" name="test">
Note: this form is being submitted to itself.
Above the form, I have the following PHP:
if (empty($_POST['test'])) {
$thevalue = 0;
} else {
$thevalue = 1;
}
var_dump($thevalue);
When I process the form, I get what I would expect. If I check the box and submit, I get int(1) if I leave it unchecked I get int(0).
In the first line of my PHP code, I wanted to replace $_POST['test'] with some simple variable.
So I added the following line above my code:
$simplevar = $_POST['test']
I then replaced the condition in my if statement to be empty($simplevar)
But when I submit the form, I get a "Notice: Undefined index:" error message
Why is this happening?
Assuming it's possible to achieve what I was after (i.e. insert $_POST into $simplevar), how might I go about it?
Thanks in advance for your help!
PS: I may have a follow up to this question, but didn't want to clutter things by jamming it all in here.
Thanks again... oh, and Merry Christmas! ;-)
This happens because when you don't check the checkbox, the browser does not send any value to server for that control when the form is submitted. Because of this, $_POST['test'] is not defined, and you tried to use it without a check as to whether it existed, so you get a warning. One of the checks that empty() does is to see whether the value is set. So, when you use the $_POST keys directly in empty(), you don't get an error, but when you try and use it in an assignment without this check, you will get the error.
You can do roughly what you want to do, you just have to change the logic slightly. If you do:
$simplevar = !empty($_POST['test']);
// You could also do
// $simplevar = isset($_POST['test']);
if ($simplevar) {
// The box was checked
} else {
// The box was not checked
}
...it will do what you want without the error. Using this approach, $simplevar always holds a boolean indicating whether or not the box was checked.
When a checkbox is unchecked, it's not added to the $_POST array as a key, which is why $simplevar = $_POST['test'] returns the error you posted. Using empty() gets past this problem by empty() handling errors better (well, silently at any rate).
You haven't specified whether you get that error when the checkbox is checked or not, but the above explanation is the only one I can give. If you're unsure, try doing print_r($_POST) to see what $_POST actually contains.
A solution to your problem would be to use a ternary expression to handle the error a little better:
$simplevar = isset($_POST['test']) ? 0 : 1;
This will assign 0 to $simplevar if $_POST['test'] isn't set (checkbox isn't checked), or 1 otherwise.
Do make sure all your form processing code is put inside
if(!empty($_POST)) {
// Code
}
So that it's not executed every time the page loads, otherwise your error will show every time.
Checkbox values are only transmitted if the checkbox was checked. This means that unchecked checkboxes won't appear in the $_POST array.
A way to suppress the notice from PHP is to use a reference instead of a variable:
$simplevar =& $_POST['test'];
if(empty($simplevar)) $thevalue = 1;
else $thevalue = 0;
That's expected behaviour. If you are assigning the variable like this:
$simplevar = $_POST['test'];
Then the $_POST variable might be absent. The Zend runtime then assigns the NULL value, but gives you a useful debug hint, should that not be what you wanted.
When you used empty() before, the check for variable existence was built in. empty() is a language construct. Like isset() it's often used to eschew such notices. The cumbersome syntax to emulate such language behaviour is:
$simplevar = empty($_POST['test']) ? NULL : $_POST['test'];
The language built-in for is:
$simplevar = #( $_POST['test'] );
Now, I will get roasted for mentioning it. (Using # is useful if you want to bring the debug notices back at some point, while the empty and isset constructs eternally suppress them.)
First, you should always check that variables in $_POST, $_REQUEST, and $_GET are set before attempting to use them. Always handle the condition where they are not set even if you simply output an error.
Because the error is an undefined index it seem the error is in test not being set in $_POST, though that doesn't make a lot of sense. I would add a check, maybe an echo or var dump to check $_POST. If it is set the other problem could be an issue with scope. $_POST is something called a super global which makes it available in any scope. Variables you set you may need to make global by defining them as such if you want to access them across scopes.

Is this an OK test to see if a variable is set

Yesterday, I posted an answer to a question that included several (unknown to me at the time) very bad code examples. Since then, I've been looking at my fundamental knowledge of PHP that allowed me to think that such code is possible. This brings me to a question that I can't seem to find an answer to:
If I want to check for whether or not a variable has anything set, is it a valid practice to not use isset() or another helper function? here's a "for instance":
if($not_set){
//do something
} else {
//do something else
}
Rather than...
if(isset($not_set)){
//do something
} else {
//do something else
}
From the name of the variable, you can see that this variable is not set. Therefore the conditional would be false and the else portion would run. Up until now I have been using this practice, but after the posts yesterday, I now have an inkling that this is wrong.
Here's why I thought that it would be an ok practice to leave out the isset() function above. From PHP manual:
The if construct is one of the most
important features of many languages,
PHP included. It allows for
conditional execution of code
fragments. PHP features an if
structure that is similar to that of
C:
if (expr) statement
As described in the section about
expressions, expression is evaluated
to its Boolean value. If expression
evaluates to TRUE, PHP will execute
statement, and if it evaluates to
FALSE - it'll ignore it. More
information about what values evaluate
to FALSE can be found in the
'Converting to boolean' section.
And from the 'Converting to boolean section':
When converting to boolean
, the following values are considered
FALSE:
...
* the special type NULL (including unset variables)
Why would the manual go out of its way to state that unset variables are included if this is a bad practice? If it's unset, it gets converted to NULL and therefore is evaluated properly by the conditional. Using isset() will find the same result, but will take extra cycles to do so.
Have I been wrong this whole time, and if so, why? (And just how bad it is, maybe?)
If the variable is not set you get a Notice. If you use isset() you don't get a notice. So from an error reporting point of view, using isset() is better :)
Example:
error_reporting(E_ALL);
if($a) {
echo 'foo';
}
gives
Notice: Undefined variable: a in /Users/kling/test on line 5
whereas
error_reporting(E_ALL);
if(isset($a)) {
echo 'foo';
}
does not output anything.
The bottom line: If code quality is important to you, use isset().
It's okay but not good practice to use if to check for a set variable. Two reasons off the top of my head:
Using isset makes the intent clear - that you're checking whether the variable is set, and not instead checking whether a condition is true.
if ($not_set) will evaluate to false when $not_set is actually set but is equal to boolean false.
You will run in to problems if your variable is set, but evaluates to FALSE, like the following:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the
string "0"
an array with zero elements
an object with zero member
variables (PHP 4 only)
the special type NULL (including
unset variables)
SimpleXML objects created from empty
tags
Taken from the PHP manual.
Basically, using isset() is showing that you are explicitly checking if a variable exists and is not NULL, while the structure of your if statement only checks if the variable is true. It is more clear and less error-prone.
It is a common practise, but is not good -- you should always use isset!
If your $not_set is set, and is a bool with the value false, your "test" will fail!
isset works as a guard preventing you from using variables that do not actually exist.
if (isset($foo)) and if ($foo) do not mean the same thing. isset just tells you if the variable actually exists and if it's okay to use it, it does not evaluate the value of the variable itself*.
Hence, you should usually use one of these two patterns:
If the variable is sure to exist and you just want to check its value:
if ($foo == 'bar')
If the variable may or may not exist, and you want to check its value:
if (isset($foo) && $foo == 'bar')
If you're just interested that a variable is set and evaluates to true, i.e. if ($foo), you can use empty:
if (isset($foo) && $foo)
// is the same as
if (!empty($foo))
* it does check for null, where null is as good as not being set at all

Categories