Why do I need the isset() function in php? - php

I am trying to understand the difference between this:
if (isset($_POST['Submit'])) {
//do something
}
and
if ($_POST['Submit']) {
//do something
}
It seems to me that if the $_POST['Submit'] variable is true, then it is set. Why would I need the isset() function in this case?

Because
$a = array("x" => "0");
if ($a["x"])
echo "This branch is not executed";
if (isset($a["x"]))
echo "But this will";
(See also http://hk.php.net/manual/en/function.isset.php and http://hk.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting)

isset will return TRUE if it exists and is not NULL otherwise it is FALSE.

You basically want to check if the $_POST[] variable has been submitted at all, regardless of value. If you do not use isset(), certain submissions like submit=0 will fail.

In your 2nd example, PHP will issue a notice (on E_NOTICE or stricter) if that key is not set for $_POST.
Also see this question on Stack Overflow.

The code
if($_POST['Submit'])
{
//some code
}
will not work in WAMP (works on xampp)
on WAMP you will have to use
if (isset($_POST['Submit'])) {
//do something
}
try it. :)

if user do not enter a value so $_post[] return NULL that we say in the description of isset:"
isset will return TRUE if it exists and is not NULL otherwise it is FALSE.,but in here isset return the true
"

Related

Correct Way to determine if function is set

i cant seem to find a solution to my issue. im trying to check if the value of a function has been set and if it has do some stuff however when i run the below codes the bottom one throws a error the code at the bottom is the code i wish to use
seems pointless calling the function into a variable just to see if its set
//working check if set
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset))
{
echo"do some stuff";
}
//NOT working check if set
if(isset( WA_FN_Validate_Post($_POST['wa_passwordreset']) ))
{
echo"do some other stuff";
}
As per PHP manual:
isset — Determine if a variable is set and is not NULL
isset actually test if a variable is set, not if a function returns any value. That is why your code doesn't work.
im trying to check if the value of a function has been set
Functions do not have values. Functions may return values. You can't check if a function has a value and if it's set.
Moreover,
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset))
{
echo "do some stuff";
}
this portion of code will always return true. The reason for that is that even if WA_FN_Validate_Post would return an empty string, the variable $wa_passwordreset will be considered set and isset check will always return true. To avoid this, you should either check your $_POST like this:
if(isset($_POST['wa_passwordreset']))
{
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
echo "do some stuff";
}
Or if it's vital for you to maintain the order and check after WA_FN_Validate_Post, use empty:
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset) && !empty($wa_passwordreset)) // be extra paranoid!
{
echo "do some stuff";
}

PHP - proper check if $_POST['variable'] is posted

I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true.
Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you
isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn't just check whether the $_POST array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that's what empty is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}
As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.
$submit = $_POST['submit'] ?? '';
If submit key does not exist or is NULL the value of the $submit variable will be an empty string.
This method is not limited to $_POST. It will work for any variable. For example:
echo $my_message ?? 'No message found';
If message was not initialized or is NULL, the statement above will output No message found
There's even more that you can do with a null coalesce operator, documentation link below.
Documentation here
$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}
As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST.

What is the best way to know is $_GET['example']=="somevalue"?

if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

Check if form element sent but empty with PHP

I'd like to separate two things.
If a $_POST["something"] was sent, BUT empty.
OR
If a $_POST["something"] was not sent.
Is there a way?
You might be tempted to use empty(), but it blows up in your face if your possible values include a 0. Best to use something like:
if (isset($_POST['something'])) {
// the form field was sent ...
if ($_POST['something'] === '') {
// the form field was sent, but is empty
}
}
This works, as ALL data coming out of the _GET/_POST/_REQUEST superglobals is a string, regardless of whether it's a number or not.
You'll want to use isset()
if (isset($_POST["something"])){
echo "The Post Variable 'something' was posted";
if (strlen($_POST["something"])==0)
echo "The Post Variable is blank";
else
echo "The Post Variable Contains ".$_POST['something'];
}
look towards isset and empty.
http://php.net/manual/fr/function.isset.php
http://php.net/manual/fr/function.empty.php
Edit : The comments below are true. Empty should be used for empty strings, not numeric values, float values or a zero in a string​​. However, here's a function if you need to accept these as valid values:
function is_blank($value) {
return empty($value) && !is_numeric($value);
}
i use the php function isset() to check if a POST was sent or not
http://php.net/manual/en/function.isset.php
if ($_POST["something"])
will return true if there is such field
if $_POST["something"] == ""
will do the rest

Checking if a constant is empty

Why is this not possible?
if(!empty( _MY_CONST)){
...
But yet this is:
$my_const = _MY_CONST;
if(!empty($my_const)){
...
define( 'QUOTA_MSG' , '' ); // There is currently no message to show
$message = QUOTA_MSG;
if(!empty($message)){
echo $message;
}
I just wanted to make it a little cleaner by just referencing the constant itself.
See the manual: empty() is a language construct, not a function.
empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
So you'll have to use a variable - empty() is really what you want in the first place? It would return true when the constant's value is "0" for example.
Maybe you need to test for the existence of the constant using defined() instead?
Just letting you know that you can do
if(!empty(MY_CONST))
since PHP 5.5.
You can get along with this if for some reason you are still not using PHP 5.5.
if (defined('MY_CONST') && MY_CONST) {
echo 'OK';
}
if (!empty(constant('MY_CONST')) {
...
}
mixed constant ( string $name )
Return the value of the constant indicated by $name, or NULL if the constant is not defined
http://php.net/manual/en/function.constant.php
what about strlen?
if(strlen(MY_CONST) == 0)
If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:
define('MY_CONST', '');
if (!MY_CONST) {
echo 'MY_CONST is empty';
}

Categories