Testing an array is empty in a if statement - php

i used this way to testing an array $arr if empty
if(!empty($arr)){ //do something }
recently, i saw someone use an another like:
if($arr){ //do something }
just want to know is't the second way a simply way to testing an array or is there some potential risk here ?

An empty array like array() is regarded as equal to false. So a simple if ($arr) works perfectly fine.
empty does the same kind of comparison, but does not trigger a NOTICE about missing variables, should the variable $arr not exist at all. You should not use empty if you are sure the variable exists, since it suppresses valuable error reporting. Only use empty if you really don't know whether a variable exists or not and have no control over it.
For more information about empty see The Definitive Guide To PHP's isset And empty.

The second casts the array to a boolean. Empty arrays are cast to false, anything else to true. So if($arr) and if(!empty($arr)) are functionally identical.

Both methods are functionally equivalent. The documentation for empty() mentions the following things are considered to be empty
"", 0, 0.0, "0", NULL, FALSE, array(), var $var;
Taking a look at casting to a bool, we can see that the list matches the list, which means both methods handle different types in the same way.

The second way is not ideal. If you use the second method and determine you're dealing with an array (and you aren't) and pass it to a foreach statement, you'll end up with an error. It is also more instructive for what you're checking to do more than test with if($arr).
My preference is:
if (is_array($arr) && count($arr) > 0) {
//work with array
}
Edit: I think my underlying point here is that the ability to test an array's existence is only part of the problem. If $arr turns out to be a string, a more robust check is needed.

Related

Replacing array_key_exists() with isset() in PHP

Knowing the differences of array_key_exists() and isset() in PHP, I see a lot of advocates on the web suggesting for replacing array_key_exists() with isset(), but I am thinking is it safe to do so?
In one project, I have the value of $var submitted by users. The value can be anything, even NULL or not set at all. I want to use !empty($var) to check if $var holds a non-empty value, but I understand that using !empty($var) alone is dangerous since if $var isn't pre-defined, PHP will throw an error.
So I have isset($var) && !empty($var) for checking whether $var holds a non-empty value.
However, things get complicated when I have a value stored in an assoc array. Compare the followings, assuming array $arr always exists but the key foo may or may not exist in $arr.
// code snipplet 1
$arr = array();
echo isset($arr['foo']);
// code snipplet 2
$arr = array();
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
Code snipplet 2 will always work but it seems clumsy and harder to read. As for code snipplet 1, I had bad experience... I wrote something like that before in the past on a development machine. It ran fine, but when I deployed the code to the production machine, it threw errors simply because key didn't exist in array. After some debugging, I found that the PHP configs were different between the development and the production machines and their PHP versions are slightly different.
So, I am thinking is it really that safe to just replace array_key_exists() with isset()? If not, what can be of better alternatives of code snipplet 2?
In one project, I have the value of $var submitted by users.
How does that work? Users shouldn't be able to set variables. They should be able to, e.g., submit form values which end up in $_POST. I repeat, they should not be able to directly create variables in your scope.
If "users" here means some sort of plugin system where people write and include PHP code… then you may want to think about defining a more stable interface than setting variables.
The value can be anything, even NULL…
Not if it's a value submitted through HTTP. HTTP has no concept of null. It's either an empty string or doesn't exist at all.
using !empty($var) alone is dangerous since if $var isn't pre-defined, PHP will throw an error
That is wrong. empty specifically exists to test a variable against false without throwing an error. empty($var) is the same as !$var without triggering an error if the variable doesn't exist.
So I have isset($var) && !empty($var) for checking whether $var holds a non-empty value.
See Why check both isset() and !empty(). (Spoiler: it's redundant.)
echo isset($arr['foo']);
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
These both do exactly the same thing. isset returns true if the value exists and its value is not null. The second line returns true if the array key exists and its value is not null. Same thing.
I had bad experience...
You'd need to be more detailed about that, since there should be no caveat to isset as you describe it.
See The Definitive Guide To PHP's isset And empty and Difference between isset and array_key_exists.

PHP if() evaluation problem needs a rewrite

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

Check whether string is set, even if it's 0

What's the best way of writing:
if(!$this->uri->segment('4') && $this->uri->segment('4') != 0)
This is far too long winded. Just need to check if a string is set, even if it's 0.
isset()
EDIT: nope this is not a var its a method..
Just need to check if a string is set, even if it's 0.
if($this->uri->segment('4') != '')
but i dont think this is what you are trying to do.
it depends on what this method returns and what you try to accomplish.
This is far too long winded. Just need to check if a string is set, even if it's 0.
How about checking for the length of the string?
if (strlen($this->uri->segment('4')) > 0)
EDIT For explicitness, I've added > 0, so it may be a little more descriptive what it is exactly you expect. This isn't necessary, however.
The first clause isn't "correct" anyway, as you've discovered by having to write the second one. You also have to consider FALSE and the empty string (""). Code like if ($var) is lazy and, usually, wrong.
The correct approach for testing a variable is the PHP function isset. However, assuming $this->uri->segment('4') is a function call, the result will always be "set". It can never not be set. So it seems unlikely to be that you can do much here.
What criteria are you really looking for?
Perhaps your function segment returns null? So write if (!is_null($this->uri->segment('4'))).
Or perhaps you're looking for the empty string? So write if ($this->uri->segment('4') != "").
1
if ( strlen($this->uri->segment('4')) )
{}
2
if ( strlen($this->uri->segment('4')) !== "" )
{}

What is the difference between null and empty?

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.

Detecting insufficient PHP variables: FALSE vs NULL vs unset() vs empty()?

What is the best way to define that a value does not exist in PHP, or is not sufficent for the applications needs.
$var = NULL, $var = array(), $var = FALSE?
And what is the best way to test?
isset($var), empty($var), if($var != NULL), if($var)?
Initializing variables as what they will be, e.g. NULL if a string, array() if they will be arrays, has some benefits in that they will function in the setting they are ment to without any unexpected results.
e.g. foreach($emptyArray) won't complain it just wont output anything, whereas foreach($false) will complain about the wrong variable type.
But it seams like an unnecessary hassle to have so many different ways of doing basically the same thing. eg. if(empty($var)) or if ($var == NULL)
Duplicate: Best way to test for a variable’s existence in PHP; isset() is clearly broken
Each function you named is for different purposes, and they should be used accordingly:
empty: tells if an existing variable is with a value that could be considered empty (0 for numbers, empty array for arrays, equal to NULL, etc.).
isset($var): tells if the script encountered a line before where the variable was the left side of an assignment (i.e. $var = 3;) or any other obscure methods such as extract, list or eval. This is the way to find if a variable has been set.
$var == NULL: This is tricky, since 0 == NULL. If you really want to tell if a variable is NULL, you should use triple =: $var === NULL.
if($var): same as $var == NULL.
As useful link is http://us2.php.net/manual/en/types.comparisons.php.
The way to tell if the variable is good for a piece of script you're coding will entirely depend on your code, so there's no single way of checking it.
One last piece of advice: if you expect a variable to be an array, don't wait for it to be set somewhere. Instead, initialize it beforehand, then let your code run and maybe it will get overwritten with a new array:
// Initialize the variable, so we always get an array in this variable without worrying about other code.
$var = array();
if(some_weird_condition){
$var = array(1, 2, 3);
}
// Will work every time.
foreach($var as $key => $value){
}
Another thing to remember is that since php is liberal in what it allows to evaluate to NULL or empty, it's necessary to use the identity operators (===, !== see http://php.net/operators.comparison. This is the reason why all of these comparison and equality functions exists, since you often have to differentiate between values with subtle differences.
If you are explicitly checking for NULL, always use $var === NULL
My vote goes for unset(), because non existing variables should generate an notice when used.
Testing gets a bit more complicated, because isset() wil be false if the variable is "not existings" or null. (Language designflaw if you'd ask me)
You could use array_key_exists() for valiables in $GLOBALS, $_POST etc.
For class properties there is property_exists().

Categories