I am working on a signup form, I am using PHP and on my processing part I run some code, if a submitted item fails I then add it to an errors array.
Below is a snip of the code, I am at the point where I need to find the best method to determine if I should trigger an error.
So if there is a value set in the error array then I need to redirect and do some other stuff.
I was thinking of using isset or else is_array but I don't think that is the answer since I set the array using **$signup_errors = array()** wouldn't this make the is_array be true?
Can anyone suggest a good way to do this?
//at the beginning I set the error array
$signup_errors = array();
// I then add items to the error array as needed like this...
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
How does it work? When converting to boolean, an empty array converts to false. Every other array converts to true. From the PHP manual:
Converting to boolean
To explicitly convert a value to
boolean, use the (bool) or (boolean)
casts. However, in most cases the cast
is unncecessary, since a value will be
automatically converted if an
operator, function or control
structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the
following values are considered FALSE:
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
Every other value is considered TRUE (including any resource).
You could also use empty() as it has similar semantics.
Perhaps empty()?
From Docs:
Return Values
Returns FALSE if var has a non-empty
and non-zero value.
The following things are considered to
be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Check if...
if(count($array) > 0) { ... }
...if it is, then at least one key-value pair is set.
Alternatively, check if the array is not empty():
if(!empty($array)) { ... }
Use array_filter if you already have keys, but want to check for non-boolean evaluated values.
<?php
$errors = ['foo' => '', 'bar' => null];
var_dump(array_filter($errors));
$errors = ['foo' => 'Oops', 'bar' => null];
var_dump(array_filter($errors));
Output:
array(0) {
}
array(1) {
["foo"]=>
string(4) "Oops"
}
Use:
<?php
if(array_filter($errors)) {
// Has errors
}
You could check on both the minimum and maximum values of the array, in this case you can have a large array filled with keys and empty values and you don't have to iterate through every key-value pair
if(!min($array) && !max($array)) { ... }
The language construct isset(), is for testing to see if variables and array elements are set and not NULL. Using is_array() would tell you if the argument you supply to it is an array. Thus, I do not think using isset() or is_array() would give you the correct and desired result that you are seeking.
The code:
$signup_errors = array();
means that ...
is_array($signup_errors);
would return true. However, this does not mean that the Boolean language rules of PHP would evaluate....
if($signup_errors)
{
//*Do something if $signup_errors evaluates to true*;
}
as true, unless some elements are added to it. When you did this,
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
you fulfilled the PHP language requirement for the array above to evaluate to true.
Now, if for some reason you wanted, or needed, to use isset() on the array elements in the future, you could. But, the conditional statement above is enough for you this case.
I should add an obvious answer here. If you initialise your error array as an empty array. And later want to check if it is no longer an empty array:
<?php
$errors = [];
if($errors !== [])
{
// We have errors.
}
Related
I face a problem like this:
$area="Dhaka";
isset($area); //returns true which is OK
isset($area['division']); //returns true why?
// actually, any array key of area returns true
isset($area['ANY_KEY']);//this is my question 1
isset($area['division']['zilla');//now it returns false.
//as I know it should returns false but why previous one was true.
Now if I do this:
$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this
isset($area['division']['ANY_KEY']); // returns true why? question #2
Basically both of my questions are the same.
Can anyone explain this?
As with every programming language in existence, a string is stored as an array of characters.
If I did:
$area = "Dhaka";
echo $area[0];
It would return D.
I could also echo the whole string by doing:
echo $area[0].$area[1].$area[2].$area[3].$area[4];
PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.
So by doing:
echo $area['division'];
You would essentially be doing:
echo $area[0];
and again, getting D.
That's why isset($area['division']) returns a true value.
Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.
The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:
is_array($area) && isset($area['division'])
PHP lets you treat a string as an array:
$foo = 'bar';
echo $foo[1]; // outputs 'a'
So
$area['division']
will be parsed/executed as
$area[0];
(the keys cannot be strings, since it's not REALLY an array, so PHP type-converts your division string by its convert-to-int rules, and gives 0), and evaluate to the letter D in Dhaka, which is obviously set.
Okay, here's a solution rather than explaining why isset isn't going to work properly.
You want to check if an array element is set based on it's index string. Here's how I might do it:
function isset_by_strkey($KeyStr,$Ar)
{
if(array_key_exists($KeyStr,$Ar))
{
if(strlen($Ar[$KeyStr]) > 0 || is_numeric($Ar[$KeyStr] !== FALSE)
{
return TRUE;
}
return FALSE;
}
}
isset_by_strkey('ANY_KEY',$area); // will return false if ANY_KEY is not set in $area array and true if it is.
The best way to access a linear array in php is
// string treated as an linear array
$string= "roni" ;
echo $string{0} . $string{1} . $string{2} . $string{3};
// output = roni
It is expected behaviour.
PHP Documentation covers this
You can try empty() instead.
If it is returning true for keys that do not exist there's nothing you can do; however, you can make sure that it doesn't have a negative effect on your code. Just use array_key_exists() and then perform isset() on the array element.
Edit: In fact, using array_key_exists() you shouldn't even need isset if it is misbehaving just use something like strlen() or check the value type if array_key_exists returns true.
The point is, rather than just saying isset($Ar['something']) do:
if(array_key_exists('something',$Ar) )
and if necessary check the value length or type. If you need to check the array exists before that of course use isset() or is_array() on just the array itself.
For validating a variable value we can do
if(empty($var)){
}
OR
This will return true on empty string, 0 as number, false, null
if(!$var){
}
What is the difference between this two approaches, are them equivalent?
EDIT: Some examples where they behave different will be more pratical.
EDIT2: The only difference founded from answers is that the second will throw a notice if $var is undefined. What about the boolean value they return?
EDIT3: for $var I mean any variable with any value, or even an undefined variable.
Conclusion from users answers:
if(!$var) and empty($var) are equivalent as described here http://php.net/manual/en/types.comparisons.php, they will return the same bool value on the same variable.
if(!$var) will return a php notice if $var is not defined, normally this is not the case (if we write good code) most IDEs will underline it.
When checking simple variables if(!$var) should be ok
When checking arrays index ($var['key']) or object properties ($var->key)
empty($var['key']) is better using empty.
the problem is that since !$vars is shorter than empty($vars) many of us will prefer the first way
You prefer the first one because it is a "shorter way"?
Shorter code does not mean better code, or faster scripts ;)
The speed of PHP functions and its various other behaviours is not determined by the length of the function name. It is determined by what PHP is actually doing to evaluate, action, and return results.
Besides that, don't choose methods based on length of code, choose methods based on scenario and best approach "for a given scenario".
Which is best depends on what you need, and there are other variable checks other than the two you mentioned (isset() for one).
but the problem is are they equivalent always
Not necessarily - see
http://php.net/manual/en/types.comparisons.php
Or create a quick test script to see what PHP returns for your two scenarios.
You could also be initialising your variables in your framework (or, likely, stand alone script), which means the scenario changes, as could your question and approach you use.
It's all contextual as to which is the best.
As for the required answer.
Anyway, to answer your question, here are some tests:
(!$vars)
Example code:
if ( !$vars )
{
echo "TRUE";
}
else
{
echo "FALSE";
}
will return:
Notice: Undefined variable: vars in /whatever/ on line X
TRUE
However, if you initialise the var in your scripts somewhere first:
$vars = "";
$vars = NULL;
$vars = 0;
Any of the above will return:
[no PHP notice]
TRUE
$vars = "anything";
will return:
FALSE
This is because with the exclamation mark you are testing if the var is FALSE, so when not initialised with a string the test script returns TRUE because it is NOT FALSE.
When we initialise it with a string then the var NOT being FALSE is FALSE.
empty($vars)
Example code:
if ( empty($vars) )
{
echo "TRUE";
}
else
{
echo "FALSE";
}
Not initialised/set at all, and all of the following:
$vars = "";
$vars = NULL;
$vars = 0;
will return:
TRUE
There is no PHP notice for using empty, so here we show a difference between the two options (and remember when I said the shortest code is not necessarily the "best"? Depends on the scenario etc.).
And as with the previous test:
$vars = "anything";
returns:
FALSE
This is the same with ( !$var ), you are testing IF EMPTY, and without the var being initialised at all, or with any "empty()" value: eg (""), or NULL, or zero (0), then testing if the var is empty is TRUE, so we get TRUE output.
You get FALSE when setting the var to a string because IS EMPTY = FALSE as we set it to something.
The difference is empty() does not throw a PHP notice when var is not defined, whereas (!$var) will.
Also, you may prefer it for being "shorter code", but if (!$var) isn't really much shorter/better looking than the widely used if (empty($var)).
But again, this depends on the scenario - PHP provides different options to suit different requirements.
No they are not equal
if(empty($var)){
echo "empty used\n";
}
if(!$var){ # line no. 6
echo "! used";
}
will output
empty used
Notice: Undefined variable: var in /var/www/html/test.php on line 6
! used
Following values are considered to be empty when using empty() function
"" (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; (a variable declared, but without a value)
As you can read in empty docs
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
They are not.
The first one verify if $var has any value.
The second one verify as boolean - if true or not.
The second one will give you a notice, the first one will be true if the value is empty for $var.
If you wish to verify if $var exists, use isset.
if( !isset($var) )
echo '$var does not exists!<br>';
if(empty($var))
echo 'The value is empty or does not exists!<br>';
if( !$var )
echo 'Value is false!<br>';
$var = '';
if(empty($var))
echo 'The value is empty or does not exists!<br>';
Use this to view the notice
error_reporting(-1);
ini_set('display_errors', 1);
The main difference is that empty() will not complain if the variable does not exist, whereas using ! will generate a warning.
In older versions of PHP, empty() only worked on direct variables, meaning this would fail:
empty($a && $b);
This has been changed in 5.5
The official manual contains all you have to know on this subject:
http://php.net/manual/en/types.comparisons.php
if (!$var) is the last column, boolean : if($x) negated.
As you can see they are the same, but empty won't complain if the variable wasn't set.
From the manual:
empty() does not generate a warning if the variable does not exist
Take some time, and study that chart.
As far as I know, it's pretty simple.
empty() is basically equivalent to !isset($var) || !$var and does not throw any warnings/notices, whereas using just !$var will throw a notice if the variable isn't defined.
For the sake of completeness, the following are considered empty when using empty():
empty strings
empty arrays
0, 0.0, '0' (int, float, string)
null
false
defined variables without a value
From a boolean value return empty is equivaliend to !:
empty($var) === !$var; // supposed that $vars has been defined here
From a notice/waning notification they are not equivalent:
empty($array['somekey']); //will be silent if somekey does not exists
!$array['somekey']; // will through a warning if somekey does not exists
I have a quick question here. I know that the cakePHP find('first') function returns an array containing the first result if found, false otherwise. My question is this, what if I were to write a check like this:
if(result_is_array) // that means I have data
{
// do something
}
else // that means result is a boolean
{
// do something else
}
Instead of checking whether the result obtained from find('first') is an array or not, can I just say:
$result = $this->MyModel->find('first');
if($result)
{
// do something
}
In order words, if I get an array here, will that evaluate to TRUE in php? Is if(array()) equal to true in php?
YES, you can do
$result = $this->MyModel->find('first');
if($result)
An array with length > 0 returns true
Explanation is here in the docs
When converting to boolean, the following values are considered FALSE
an array with zero elements
Every other value is considered TRUE
A zero value array is false
An array with values in it is true
You can view this table to see what is evaluated as true vs false.
Instead of checking whether the result obtained from find('first') is
an array or not
Yes. Do it the second way:if ($result). If find returns an empty array or boolean false, the branch will not be executed.
The best part about doing it this way is that it makes it clear to the reader that you are checking for a non-empty value.
According to the documentation, if you try to treat an array as a boolean, the array will be considered true precisely when it's not empty.
Use the following if you are looking for a TRUE value:
if ( $result !== false )
{
// do something
}
An empty array will always evaluate to false or if it contain any key/values then it will evaluate to true. if $this->MyModel->find('first'); always returns an array then an empty result will evaluate to false and true other wise. so your code is perfectly valid.
I have very basic question regarding return value of a function, and checking the variable value.
function test($var1, $var2){
if ($var1 == $var2){
$var3 = "abc";
return $var3;
}
return false
}
$value = test($var1, $var2);
if ($value){
echo "Value is".$value; //should output abc.
} else {
echo "Not equal";
}
Is it ok to either return a value or return false? For example I am not returning TRUE, it is ok?
When i call the function, i store the return value in a variable $value. How can i check the function did return the $var3? Which of the if condition should be used?
if (!empty($value)) or if (isset($value)) or if ($value) or if (value != false)
Yes, it is common practice in PHP to return FALSE as an indicator of an error condition. (What constitutes an error is your own decision and depends on what the function is supposed to do.)
However, since PHP automatically casts values to Boolean that are of another type (like the empty string or 0, which evaluate to FALSE as well), you should do an explicit check for FALSE like this:
if ($value !== FALSE) ...
As Felix Kling notes in the comments, this is called "strict comparison" (or "identity comparison"). It checks if a value is identical to FALSE, where as != FALSE, == FALSE and if ($value) only check if a value could be interpreted as FALSE.
I'm not a PHP developer, but I don't think your first approach works.
There are other things than the boolean value false interpreted as false:
When converting to boolean, the following values are considered FALSE:
* 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
http://php.net/manual/en/language.types.boolean.php
It's perfectly OK to return different data types.
If you want to check against false, use: if ($value !== false). If you get lost which condition to use, this will clarify it: http://www.php.net/manual/en/types.comparisons.php
Your function returns false, so I would go with that check: if ($value != false)
$var3 = "abc";
return $var3;
That's pointless. You're returning a value, not a variable. return "abc"; is perfectly fine.
Is it ok to either return a value or return false?
Yes, that's perfectly fine for a simple case such as this.
How can i check the function did return the $var3?
As said above, the function returns the value "abc", not $var3. You're saving it in a new variable $value. This variable is definitely set (you just created it right there), so there's no need for isset or empty. Just test whether its value is true or false (or whatever else you want to test for). So the way you're doing it in fine.
Yes, you can return pretty much anything from the function, or you can just "return" without returning anything. In your example, you'll get a string or "false" in return.
To check for false you either do if (!$variable) or if ($variable===false). Zero will return true if you do "if ($variable==false)" due to auto casting of zero to false (and any other positive number to true). Three "===" makes sure it really is false and nothing else. The isset($var) checks for existance, not value - and is not applicable to your example since your function will return a value or "false" and thus always exists.
The only right answer here is: it depends.
I always ask myself this question when creating a function like this. To answer it, I analyze what the function does, instead of what it returns.
For instance, if I have a getter, I expect to get a value, or nothing. In this case I often return null when nothing is found/something went wrong.
A test function like yours should return a boolean at all times, in my opinion. Returning a variable when you're checking for something to be true or false is semantically incorrect, I think.
Aside from the semantics: returning 0, false or null does not really matter when you're checking it with if (test($var1, $var2)), since it will all work the same. However, if you want some finer details, you want to do an identity check (===) rather than a equality check. In PHP this is sometimes the case, for instance strpos can return 0 or false, 0 being a match is found, and false is not. Therefore the following would fail:
// returns 0, which is casted to false, so the 'else' part is executed
if (strpos('a', 'abc')) {
// 'abc' contains 'a'
} else {
// 'abc' does not contain 'a'
}
So, long story short: it depends...
I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.
So you can use empty() to check that a user typed something.
Is it true that the isset() function treats an empty string as TRUE?
Then in which situations should I use isset()? Should I always use !empty() to check if there is something?
For example instead of
if(isset($_GET['gender']))...
Using this
if(!empty($_GET['gender']))...
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.
On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
In the most general way :
isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
empty tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty.
Neither is a good way to check for valid input.
isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
! empty() is not sufficient either because it rejects '0', which could be a valid value.
Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:
if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).
For that, see Josh Davis's answer.
isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.
So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:
$var = "";
var_dump(isset($var));
The type comparison tables in PHP’s manual is quite handy for such questions.
isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
isset() is not an effective way to validate text inputs and text boxes from a HTML form
You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.
Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.
When and how to use:
isset()
True for 0, 1, empty string, a string containing a value, true, false
False for null
e.g
$status = 0
if (isset($status)) // True
$status = null
if (isset($status)) // False
Empty
False for 1, a string containing a value, true
True for null, empty string, 0, false
e.g
$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
isset() vs empty() vs is_null()
isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...
Pascal MARTIN... +1
...
empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
isset($variable) === (#$variable !== null)
empty($variable) === (#$variable == false)
I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is '' or null, because:
Request URL .../test.php?var= results in $_GET['var'] = ''
Request URL .../test.php results in $_GET['var'] = null
isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').
empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.
If you want to treat '0' as empty, then use empty(). Otherwise use the following check:
$var .'' !== '' evaluates to false only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}
Using empty is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the # prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && #$_GET['var']!='' ){
//Is not empty, do something
}
$var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
echo '$var is set even though it is empty';
}
Source: Php.net
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Please consider behavior may change on different PHP versions
From documentation
isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php
empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php
(empty($x) == (!isset($x) || !$x)) // returns true;
(!empty($x) == (isset($x) && $x)) // returns true;
When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.
if(empty($yourVal)) {
echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
echo "<P>YES isset - $yourVal"; // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}