php empty not empty
I would like to display some html code if a variable is not empty, else I would like to display nothing.
I’ve tried this code but doesn’t work:
9 Answers 9
isset will return true even if the variable is «». isset returns false only if a variable is null. What you should be doing:
This will check that he variable is not empty.
You don’t need isset or empty since you know the variable exists, since you have just set it in the previous line.
I don’t see how if(!empty($var)) can create confusion, but I do agree that if ($var) is simpler. – vanneto Mar 8 ’12 at 13:33
Because empty has the specific purpose of suppressing errors for nonexistent variables. You don’t want to suppress errors unless you need to. The Definitive Guide To PHP’s isset And empty explains the problem in detail. – deceze♦ Mar 9 ’12 at 1:24
Focusing on the error suppression part, if the variable is an array where a key being accessed may or may not be defined:
Notice: Undefined index: status
So if zero is a meaningful status that you want to detect, you should actually use string and numeric comparisons:
Error free and zero detection:
Fixing the PHP empty function
PHP has the habit of evaluating (int)0 and (string)»0″ as empty when using the empty() function. This can have unintended results if you expect numerical or string values of 0. How can I «fix» it to only return true to empty objects, arrays, strings, etc?
13 Answers 13
This didn’t work for me.
I seldom use empty() for the reason you describe. It confuses legitimate values with emptiness. Maybe it’s because I do a lot of work in SQL, but I prefer to use NULL to denote the absence of a value.
You can also use the exactly equals operator === to do a similar test:
I always add to my codebase
and use it instead of empty(). It solves the issue of keeping zeros (int, float or string) as non-empty.
«Fixing» is one point of view. Another would be to assume it’s not «broken», and learn to work with it the way it was intentionally designed.
Given the problem as you describe it, the best thing would be to tighten up your code so the variable can’t be put into an indeterminate type state. Otherwise, you’ll want to test for datatype using gettype().
Generally speaking you want to use the triple equals operator to determine when a value truly is null or false. This is more specific and the results ALWAYS return exactly as expected.
Creating a separate function to do something that you can do in a single line of code but using a different operator seems to be overly complicated and adds additional obfuscation.
Additionally, many programmers tend to use 0 or an empty string to denote a non-existent value but it is more correct (and I feel a better practice) to use a null value to denote any value (regardless of type) that is truly non-existent.
How to check that an object is empty in PHP?
How to find if an object is empty or not in PHP.
12 Answers 12
You can cast to an array and then check if it is empty or not
Edit: I didn’t realize they wanted to specifically check if a SimpleXMLElement object is empty. I left the old answer below
Updated Answer (SimpleXMLElement):
If by empty you mean has no properties:
If SimpleXMLElement is one level deep, and by empty you actually mean that it only has properties PHP considers falsey (or no properties):
If SimpleXMLElement is more than one level deep, you can start by converting it to a pure array:
Old Answer (simple object):
If you want to check if a simple object (type stdClass ) is completely empty (no keys/values), you can do the following:
Edit: added example
You can cast your object into an array, and test its count like so:
Imagine if the object is not empty and in a way quite big, why would you waste the resources to cast it to array or serialize it.
This is a very easy solution I use in JavaScript. Unlike the mentioned solution that casts an object to array and check if it is empty, or to encode it into JSON, this simple function is very efficient concerning used resources to perform a simple task.
Using empty() won’t work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared.
Therefore you can use count() (if the object is Countable).
Another possible solution which doesn’t need casting to array :
there’s no unique safe way to check if an object is empty
php’s count() first casts to array, but casting can produce an empty array, depends by how the object is implemented (extensions’ objects are often affected by those issues)
If you cast anything in PHP as a (bool), it will tell you right away if the item is an object, primitive type or null. Use the following code:
in PHP version 8
consider you want to access a property of an object, but you are not sure that the object itself is null or not and it could cause error. in this case you can use Nullsafe operator that introduced in php 8 as follow:
If an object is «empty» or not is a matter of definition, and because it depends on the nature of the object the class represents, it is for the class to define.
PHP itself regards every instance of a class as not empty.
In short, you will have to come up with your own criteria for a specific object, and test them accordingly, either from outside the object or from a self-written isEmpty() method in the object.
php EMPTY not working correctly
I am trying to display a form ONLY if the current row is empty.. Currently the row in my DB is NOT empty. It has a date in it.. 2/10/16 it is set as a VARCHAR though. Anyways, When I use the following.. It still shows me the form even though it shouldnt because the row is NOT empty..
All variable names are correct and spelled correctly.
The select statement is working aswell, Already tested.. I feel it has to do with empty and the data in teh db being a date. 2/10/16
1 Answer 1
You need to use a while loop:
and make sure that those empty rows, if empty. are indeed empty.
Alternatively and as stated by Luke in comments, different PHP versions could empty() differently.
or another alternative:
and inside that while loop.
IMPORTANT: Make sure you do not have a default value for the column. If that default value is 0 or NULL or other, then that could affect your query and will never be considered as being empty.
Another to check for, is if your UPDATE didn’t introduce any whitespace. If the said column contains a space, then that will also be considered as «not empty». This being the fact upon testing for that also.
Edit:
After testing, your query may be failing because you are selecting all of your columns with SELECT * rather than the giventoatpdate column itself.
This being that there are other columns that are not empty.
Therefore, you may need to select the column itself only in the query:
However, make sure you did select the right column.
How to check whether an array is empty using PHP?
21 Answers 21
If you just need to check if there are ANY elements in the array
If you need to clean out empty values before checking (generally done to prevent explode ing weird strings):
An empty array is falsey in PHP, so you don’t even need to use empty() as others have suggested.
Some decent answers, but just thought I’d expand a bit to explain more clearly when PHP determines if an array is empty.
An array with a key (or keys) will be determined as NOT empty by PHP.
As array values need keys to exist, having values or not in an array doesn’t determine if it’s empty, only if there are no keys (AND therefore no values).
So checking an array with empty() doesn’t simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.
So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name=»array[]» ).
A non empty array will be produced for each field as there will be auto incremented key values for each form field’s array.
Take these arrays for example:
If you echo out the array keys and values for the above arrays, you get the following:
ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]
ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]
And testing the above arrays with empty() returns the following results:
ARRAY TWO:
$ArrayTwo is not empty
ARRAY THREE:
$ArrayThree is not empty
An array will always be empty when you assign an array but don’t use it thereafter, such as:
This will be empty, ie PHP will return TRUE when using if empty() on the above.
In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.
However it is not the best method if you simply need to know «if values exist» returns TRUE or FALSE. There are various methods to determine if an array has any values when it’s know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).
Here’s an approach which uses very little code to check if an array has values:
Using array_filter() :
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:
ARRAY TWO:
$arraytwo is not empty
ARRAY THREE:
$arraythree is empty
So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don’t need to loop through it for any other reason, then this is the simplest in terms of code needed.
I’m not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.
Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.
If you’d like to exclude the false or empty rows (such as 0 => » ), where using empty() will fail, you can try:
array_filter() : If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.
If you’d like to remove all NULL, FALSE and empty strings ( » ), but leave zero values ( 0 ), you can use strlen as a callback, e.g.:
If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:
I ran the benchmark included at the end of the post. To compare the methods:
and got the following results
The difference between empty and casting to a boolean are insignificant. I’ve run this test multiple times and they appear to be essentially equivalent. The contents of the arrays do not seem to play a significant role. The two produce the opposite results but the logical negation is barely enough to push casting to winning most of the time so I personally prefer empty for the sake of legibility in either case.
Why has no one said this answer:
if you are to check the array content you may use:
In my opinion the simplest way for an indexed array would be simply:
An ‘if’ condition on the array would evaluate to true if the array is not empty and false if the array is empty. This is not applicable to associative arrays.
But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.
You can use array_filter() which works great for all situations:
Making the most appropriate decision requires knowing the quality of your data and what processes are to follow.
Might your string value contain a 0 that you want to deem true/valid/non-empty? If so, then you only need to check if the column value has length.
Why have I gone to such length to explain this very basic task?