This question already has answers here:
Why check both isset() and !empty()
(10 answers)
Closed 12 months ago.
When coding php I try to avoid as many warnings as possible. There is one question that bugs me for quite some time now, regarding arrays.
When working with arrays and their values I often check for empty values first before I go to the "real work".
if(array_key_exists('bla', $array){
if( !empty($array['bla']) {
# do something
}
}
My Question is:
This is a lot of code for just checking if I have values to work with. Is there some shorter way to check a value within an array that may or may not exist?
Don't use empty unless you are sure that's what you want:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
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; (a variable declared, but without a value)
The manual doesn't explicitly list the "if var doesn't exist" cases, but here are a couple:
$array['undeclaredKey'] (an existing array, but key not declared)
$undeclaredVar; (a variable not declared)
Usually the array_key_exists check should suffice.
If you are checking for a non-empty value, then you can just use !empty($array['bla']).
You can also use isset($array['bla']), which returns false when: 1) key is not defined OR 2) if the value stored for the key is null. The only foolproof way to check if the array contains a key (even if its value is null) is to use array_key_exists().
The call to empty() is safe even if the key exists (behaves like isset()), so you don't have to protect it by the array_key_exists().
I am surprised this was not mentioned, but the shortest way fetch a value for a key without generating a warning/error is using the Error Control Operator:
// safely fetch from array, will return NULL when key doesn't exist
$value = #$array['bla'];
This allows you get the value for any key with the possibilty of its return value being null if the key does not exist.
You can simply do
if (!empty($array['bla']) {
# do something
}
I use that all the time in drupal and is good way to check if is available and avoid any kind of warnings.
Just do:
if (!empty($array['bla'])) {
There will be no warning if the key doesn't exist.
Not sure why no one mentioned isset yet, but you could do something like this:
// Before
if(array_key_exists('bla', $array){
if( !empty($array['bla']) {
// After (if element of array is scalar)
// Avoids warning and allows for values such as 0
if ((true === isset($array['bla'])) && (mb_strlen($array['bla']) > 0)) {
// After (if element of array is another array
// Avoids warning and ensures element is populated
if ((true === isset($array['bla'])) && (count($array['bla']) > 0)) {
If you really want to get crazy with a better way of checking vars, you could create a standardized API, below are a few methods I created to avoid laundry list function calls for variable checking:
class MyString
{
public static function populated($string)
{
//-----
// Handle various datatypes
//-----
// Don't want to assume an array as a string, even if we serialize then check
if (is_array($string)) {
return false;
}
if (is_object($string)) {
if (!is_callable(array($string, '__toString'))) {
return false;
}
$string = (string) $string;
}
//-----
return (mb_strlen($string) > 0) ? true : false;
}
}
class MyArray
{
public static function populatedKey($key, $array, $specificValue = null, $strict = true)
{
if ((is_array($array)) &&
(array_key_exists($key, $array))) {
if (is_array($array[$key])) {
return (count($array[$key]) > 0) ? true : false;
}
elseif (is_object($array[$key])) {
return true;
}
elseif (mb_strlen($array[$key]) > 0) {
if (!is_null($specificValue)) {
if ($strict === true) {
return ($array[$key] === $specificValue) ? true : false;
} else {
return ($array[$key] == $specificValue) ? true : false;
}
}
return true;
}
}
return false;
}
}
// Now you can simplify calls
if (true === MyArray::populatedKey('bla', $array)) { // Do stuff }
if (true === MyString::populated($someString)) { // Do stuff }
There are 1K ways to skin a cat, but standardizing calls like this increase Rapid Application Development (RAD) quite a bit, keeps the calling code clean, and helps with self documentation (semantically logical).
Related
I have a situation where I want to check for a key 2 levels deep in a PHP array. So my code currently looks like...
if(array_key_exists($needleBox, $haystack)) {
if(array_key_exists($needle, $haystack[$needleBox])) {
// do stuff with value attached to $needle
}
}
Where I first check for the array containing my needle ($needleBox), then check for the needle if $needleBox is found.
Is it safe to skip the check for $needleBox & use...
if(array_key_exists($needle, $haystack[$needleBox])) {
// do stuff with value attached to $needle
}
or to check for both together in one if statement like...
if(array_key_exists($needleBox, $haystack) && array_key_exists($needle, $haystack[$needleBox])) {
// do stuff with value attached to $needle
}
I consider the first alternative preferable for being more concise.
why dont you use isset. which i much more prefer it.. isset is much faster than array_key_exists. BTW isset will return false if the value is null..
if (isset($haystack[$needleBox]) && isset($haystack[$needleBox][$needle])) {
//code
}
OR
if ($haystack[$needleBox][$needle] ?? null)) {
//code
}
EDIT agreed with #shawn advise
if (isset($haystack[$needleBox][$needle])) {
//code
}
The point is to validate, only when,
$this->data[$this->alias]['enabled']
It's equal to one. So, if $this->data[$this->alias]['enabled'] == 1, validate.
I was expecting that this peace of code, would do the job:
public function compareDates() {
if ($this->data[$this->alias]['enabled'] == 1) {
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}
}
However it seems that that doesn't work as I expected. Instead, it gets always validated, regardless the value of $this->data[$this->alias]['enabled']
This code, however, seems to do the job just fine:
public function compareDates() {
if ($this->data[$this->alias]['enabled'] != 1) return true; // we don't want to check
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}
What is, in your understanding, the meaning of "we don't want to check"?
Why: if ($this->data[$this->alias]['enabled'] == 1) is not enough?
Can anyone care to explain?
Update:
If I do:
public function compareDates()
{
if ($this->data[$this->alias]['enabled'] === "1") {
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
} else {
return true;
}
}
It works as well. My question is:
Why do I need to explicitly declare the return true?;
You're doing a simple comparison (==) so PHP is looking for "truthy" statements. So ANY value that is not "falsey" will evaluate your statement (i.e. 0, false, empty strings, NULL). You can find a complete list here.
The best way around this is to use equivalency to ensure it's the exact value you want
if ($this->data[$this->alias]['enabled'] === 1)
That will force PHP to look for an integer of 1. Be aware, though, that your value MUST be the same. In other words
if('1' === 1)
Is always false because string 1 is not the same as integer 1
In this snippet of code we type $inputs['user_id'] 3 times.
if (isset($inputs['user_id']) && $inputs['user_id']) { // The consumer is passing a user_id
doSomethingWith($inputs['user_id']);
}
What's the most readable and robust refactoring I can do to avoid the duplication and avoid any notice that the index user_id doesn't exist?
Thanks.
Here nothing is wrong with the duplication. You cannot assign $inputs['user_id'] to a variable before checking if it is set, otherwise this will produce a Notice undefined index ....
The only thing here could be done is to omit the isset call and use !empty instead, like this:
if(!empty($inputs['user_id'])) {
doSomething($inputs['user_id']);
}
Now You are only typing it twice and the check
!empty($inputs['user_id'])
equals to
isset($inputs['user_id']) && $inputs['user_id']
EDIT: based on a comments, here is a quote from documentation:
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; (a variable declared, but without a value)
So either empty(0) or empty('0') will return true, that means
if(!empty('0') || !empty(0)) { echo "SCREW YOU!"; }
will echo nothing... Or, in polite way, I will repeat the statement above:
!empty($inputs['user_id']) === (isset($inputs['user_id']) && $inputs['user_id'])
EDIT 2:
By omitting the isset and replacing by !empty the variable is still checked, whether the index is already set, please read the documentation, which says:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
What about this:
// put validation check to the function body
function doSomethingWith($userId) {
if($userId === -1) {
// if this is not a valid user id -> return
return;
}
// do something ...
}
// initalize $user with proper default values.
// doing so you can be sure that the index exists
$user = array(
'id' => -1,
'name' => '',
...
);
// merge inputs with default values:
$user = array_merge($user, $request);
// now you can just pass the value:
doSomethingWith($user['id']);
Below might not be the best way for every situation, but definitely cuts down on the repetition.
Your example code would turn into:
doSomethingWith($inputs['user_id']);
and your function would look like this (notice the argument supplied by reference, to avoid the undefined variable warning):
function doSomethingWith(&$userID) {
if (empty($userID)) return;
// ... actual code here ...
}
Assuming that 0 and "" and null are not valid user_ids:
if ($id = $inputs['user_id']) {
doer($id);
}
YOu can also do with evil # to avoid notice in your logs, (I don't like this way):
if ($id = #$inputs['user_id']) {
doer($id);
}
This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I have the following code
<?php
$error = array();
$error['something'] = false;
$error['somethingelse'] = false;
if (!empty($error))
{
echo 'Error';
}
else
{
echo 'No errors';
}
?>
However, empty($error) still returns true, even though nothing is set.
What's not right?
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.
Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
Try to check it's size with sizeof if 0 no elements.
PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.
If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.
$set_errors = array_keys( $errors, true );
You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.
array with zero elements converts to false
http://php.net/manual/en/language.types.boolean.php
However, empty($error) still returns true, even though nothing is set.
That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.
From the PHP-documentation:
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 (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)
function empty() does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye
(sorry for my english)
hi array is one object so it null type or blank
<?php
if($error!=null)
echo "array is blank or null or not array";
//OR
if(!empty($error))
echo "array is blank or null or not array";
//OR
if(is_array($error))
echo "array is blank or null or not array";
?>
I can't replicate that (php 5.3.6):
php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)
php > $error = array();
php > var_dump(empty($error));
bool(true)
php >
exactly where are you doing the empty() call that returns true?
<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject) function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true
Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. 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; (a variable declared, but without a value)
For more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {