I am checking a value to see if it is empty using the empty() function in PHP. This validates the following as 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 value I am passing can be a string, array or number. However if a string has a space (" ") it is not considered empty. What is the easiest way to check this condition as well without creating my own function? I cannot just do an empty(trim($value)) since $value can be an array.
EDIT: I am not trying to ask how to check if a string is empty. I already know that. I am asking if there is a way that I can pass an array, number or string to empty() and it will return the correct validation even if the string passed has empty spaces in them.
Just write an own isEmpty() function that fits your needs.
function isEmpty($value) {
if(is_scalar($value) === false)
throw new InvalidArgumentException('Please only provide scalar data to this function');
if(is_array($value) === false) {
return empty(trim($value));
if(count($value) === 0)
return true;
foreach($value as $val) {
if(isEmpty($val) === false)
return false;
}
return false;
}
The best way is to create your own function, but if you really have a reason not to do it you can use something like this:
$original_string_or_array = array(); // The variable that you want to check
$trimed_string_or_array = is_array($original_string_or_array) ? $original_string_or_array : trim($original_string_or_array);
if(empty($trimed_string_or_array)) {
echo 'The variable is empty';
} else {
echo 'The variable is NOT empty';
}
I really prefer the function TiMESPLiNTER made, but here is an alternative, without a function
if( empty( $value ) or ( !is_array( $value ) and empty( trim( $value ) ) ) ) {
echo 'Empty!';
}
else {
echo 'Not empty!';
}
Note that, for example $value = array( 'key' => '' ) will return Not empty!. Therefor, I'd suggest to use TiMESPLiNTERs function.
Related
I'm not sure why, but some blank values still filter through my if statement... As when I do echo a json encoded version, some values have "keys" but "values" do not contain anything. Any thoughts?
function graph_fees($competitors, $fee_graph_data){
foreach ($competitors as $competitor) {
if (!empty($competitor->minSingleCareFee)) {
$fee_graph_data[$competitor->Home_name] = $competitor->minSingleCareFee;
}
}
return $fee_graph_data;
}
$mm_fees = graph_fees($competitors, $fee_graph_data);
echo json_encode($mm_fees);
Whitespace may of creeped in when creating the data, trim() it before your check.
<?php
function graph_fees($competitors, $fee_graph_data = array())
{
foreach ($competitors as $competitor) {
$competitor->Home_name = trim($competitor->Home_name);
$competitor->minSingleCareFee = trim($competitor->minSingleCareFee);
if (!empty($competitor->minSingleCareFee) && !empty($competitor->Home_name)) {
$fee_graph_data[$competitor->Home_name] = $competitor->minSingleCareFee;
}
}
return $fee_graph_data;
}
$mm_fees = graph_fees($competitors, $fee_graph_data);
echo json_encode($mm_fees);
?>
foreach ($competitors as $competitor) {
$myValue = trim($competitor->minSingleCareFee);
if (!empty($myValue)) {
$fee_graph_data[$competitor->Home_name] = $competitor->minSingleCareFee;
}
}
A string containing blanks is not empty. As of php doc:
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, if things fall through your if, $competitor->minSingleCareFee does contain something.
Try
if ( isset($competitor->minSingleCareFee)
&& trim($competitor->minSingleCareFee) != false ) {
which will skip values like " " or "\n"
My array looks like this
Array ( [] => )
To me it is empty, and I am looking for a way to check that.
First thought:
if( empty($array) ){
echo 'Array is empty!';
}
To the empty-function, my array is not empty. A 'real' empty array looks like this: Array().
Second thought:
if( $array[''] == '' ){
echo 'Array is empty!';
}
This is true for my empty array, but throws an error with any other array that does not contain such an empty key-value pair.
Any ideas?
Var_dump of my array:
array(1) { [""]=> NULL }
Quick workaround for you:
$array = array_filter($array);
if (empty($array)) {
echo 'Array is empty!';
}
array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false
EDIT 1:
In case you want to keep 0 you must use callback function. It will iterate 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.
function customElements($callback){
return ($callback !== NULL && $callback !== FALSE && $callback !== '');
}
$array = array_filter($array, "customElements");
var_dump($array);
Usage:
$array = array_filter($array, "customElements");
if (empty($array)) {
echo 'Array is empty!';
}
It will keep 0 now, just what you were asking about.
EDIT 2:
As it was offered by Amal Murali, you could also avoid using function name in the callback and directly declare it:
$array = array_filter($array, function($callback) {
return ($callback !== NULL && $callback !== FALSE && $callback !== '');
});
I don't know why you would want to have that array or what problem code generated it, but:
if(empty(array_filter($array))) {
echo 'Array is empty!';
}
Obvious check:
if(empty($array) || (count($array) == 1 && isset($array['']) && empty($array['']))) {
echo 'Array is empty!';
}
take a look at these calls:
$a = Array(null => null);
$x = (implode("", array_keys($a)));
$y = (implode("", array_values($a)));
you can control data "emptyness" with them (keys, vals or both)
EDIT: this will return as empty:
$a = Array(null => false);
too, I guess this is a problem for you
I have an array
$data = array( 'a'=>'0', 'b'=>'0', 'c'=>'0', 'd'=>'0' );
I want to check if all array values are zero.
if( all array values are '0' ) {
echo "Got it";
} else {
echo "No";
}
Thanks
I suppose you could use array_filter() to get an array of all items that are non-zero ; and use empty() on that resulting array, to determine if it's empty or not.
For example, with your example array :
$data = array(
'a'=>'0',
'b'=>'0',
'c'=>'0',
'd'=>'0' );
Using the following portion of code :
$tmp = array_filter($data);
var_dump($tmp);
Would show you an empty array, containing no non-zero element :
array(0) {
}
And using something like this :
if (empty($tmp)) {
echo "All zeros!";
}
Would get you the following output :
All zeros!
On the other hand, with the following array :
$data = array(
'a'=>'0',
'b'=>'1',
'c'=>'0',
'd'=>'0' );
The $tmp array would contain :
array(1) {
["b"]=>
string(1) "1"
}
And, as such, would not be empty.
Note that not passing a callback as second parameter to array_filter() will work because (quoting) :
If no callback is supplied, all entries of input equal to FALSE (see
converting to boolean) will be removed.
How about:
// ditch the last argument to array_keys if you don't need strict equality
$allZeroes = count( $data ) == count( array_keys( $data, '0', true ) );
Use this:
$all_zero = true;
foreach($data as $value)
if($value != '0')
{
$all_zero = false;
break;
}
if($all_zero)
echo "Got it";
else
echo "No";
This is much faster (run time) than using array_filter as suggested in other answer.
you can loop the array and exit on the first non-zero value (loops until non-zero, so pretty fast, when a non-zero value is at the beginning of the array):
function allZeroes($arr) {
foreach($arr as $v) { if($v != 0) return false; }
return true;
}
or, use array_sum (loops complete array once):
function allZeroes($arr) {
return array_sum($arr) == 0;
}
#fireeyedboy had a very good point about summing: if negative values are involved, the result may very well be zero, even though the array consists of non-zero values
Another way:
if(array_fill(0,count($data),'0') === array_values($data)){
echo "All zeros";
}
Another quick solution might be:
if (intval(emplode('',$array))) {
// at least one non zero array item found
} else {
// all zeros
}
if (!array_filter($data)) {
// empty (all values are 0, NULL or FALSE)
}
else {
// not empty
}
I'm a bit late to the party, but how about this:
$testdata = array_flip($data);
if(count($testdata) == 1 and !empty($testdata[0])){
// must be all zeros
}
A similar trick uses array_unique().
You can use this function
function all_zeros($array){//true if all elements are zeros
$flag = true;
foreach($array as $a){
if($a != 0)
$flag = false;
}
return $flag;
}
You can use this one-liner: (Demo)
var_export(!(int)implode($array));
$array = [0, 0, 0, 0]; returns true
$array = [0, 0, 1, 0]; returns false
This is likely to perform very well because there is only one function call.
My solution uses no glue when imploding, then explicitly casts the generated string as an integer, then uses negation to evaluate 0 as true and non-zero as false. (Ordinarily, 0 evaluates as false and all other values evaluate to true.)
...but if I was doing this for work, I'd probably just use !array_filter($array)
I am learning php and read this example in this http://www.php.net/manual/en/language.types.boolean.php tutorial,
I want to understand what occur when assigning the return value of method to a variable, why it may change?? please see my questions in the code.
<?php
public function myMethod()
{
return 'test';
}
public function myOtherMethod()
{
return null;
}
if($val = $this->myMethod())
{
// $val might be 1 instead of the expected 'test'
** why it may returns 1??**
}
if( ($val = $this->myMethod()) )
{
// now $val should be 'test'
}
// or to check for false
if( !($val = $this->myMethod()) ) **what happens here????**
{
// this will not run since $val = 'test' and equates to true
}
// this is an easy way to assign default value only if a value is not returned:
if( !($val = $this->myOtherMethod()) ) **what happens here????**
{
$val = 'default'
}
?>
In this case:
if($val = $this->myMethod())
{
// $val might be 1 instead of the expected 'test'
}
I don't think that's true. $val should be 'test' here. Maybe in older versions of PHP there could have been a bug.
if(!($val = $this->myMethod()))
{
// this will not run since $val = 'test' and equates to true
}
Here myMethhod() is executed and returns 'test' which is assigned to $val. Then the result of that assignment is boolean negated. Since the string 'test' evaluates to true, !('test') evalutes to false and the if statement doesn't run.
if(!($val = $this->myOtherMethod()))
{
$val = 'default';
}
This is the opposite case. $val becomes null. And null evaluates to boolean false, so !(null) evaluates to true and the code in the block executes. So after this code runs $val contains 'default'; This poster is showing this as a way of assigning a default value to $val in the case that $this->myOtherMethod() fails to return anything useful.
why it may returns 1? It is not returning 1 but the actual value that is 'test' but since this value is assigned properly because this is not NULL, false or empty. the if statement evaluates to true.
// or to check for false
if( !($val = $this->myMethod()) ) **what happens here????**
{
// this will not run since $val = 'test' and equates to true
}
What is happening here? The if statement here will test if non NULL value has been assigned to $val i.e. $val is not null similar to if(!$val). Since its value is not NULL nor false The code inside if will not execute.
if( !($val = $this->myOtherMethod()) ) **what happens here????**
{
$val = 'default'
}
What is happening here? since the assignment to the $val inside if statement failed because function returned NULL, and since $val is NULL if statement evaluates true and code inside executes. It wouldn't execute if the function had returned other than NULL or false.
Sorry guys, but i think the previous answers are wrong. I'm not sure if this is a typo or a trick question, but with
if($val = $this->myMethod())
you're actually SETTING $val to whatever $this->myMethod() returns, so your if() statement always equals true here. if you want to compare it you would have to use
if($val == $this->myMethod())
Notice the '==' in here!
Try This:
public function myMethod()
{
return 'test';
}
public function myOtherMethod()
{
return null;
}
if($val = myMethod())
{
Do Something
}elseif ($val != myMethod()){
Do Something Else
}elseif ($val == myOtherMethod())
{
$val = 'default';
}
?>
I have the following PHP code:
$required_fields = array ('menu_name','visible','position');
foreach($required_fields as $fieldname)
{
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname]) )
{
$errors [] = $fieldname;
}
}
menu_name, visible and position are variables that are received through the post method.
When the value of visible is zero, it creates an entry into the error array.
What is the best way to detect if a variable is empty when 0 is considered "not empty"?
From PHP's manual:
empty() returns FALSE if var has a
non-empty and non-zero value.
Do something like this:
if ( !IsSet ( $_POST['field'] ) || Trim ( $_POST['field'] ) == '' )
this will ensure that the field is set and that it does not contain a empty string
In essence: it is the empty() that is causing your problems not IsSet()
Since user data is sloppy, I use a custom function that treats empty spaces as non data. It sounds like this will do exactly what you want. This function will consider "0" to be valid (aka non-empty) data.
function isNullOrEmpty( $arg )
{
if ( !is_array( $arg ) )
{
$arg = array( $arg );
}
foreach ( $arg as $key => $value )
{
$value = trim($value);
if( $value == "" || $value == null )
{
return true;
}
}
return false;
}
Please note it supports arrays too but requires that each value in the array contains data, which can be useful as you can just do something like this:
$required = array( $_POST['name'], $_POST['age'], $_POST['weight'] );
if ( isNullOrEmpty($required) )
{
// required data is missing
}
PS: keep in mind this function will fire off PHP warnings if the value isn't set and there's no easy way around that, but you should NOT have warnings enabled in production anyways.
If you want to assure an array key is present you can use array_key_exists() instead of empty()
The check will become a concatenation of is_array() and array_key_exists(), being paranoid of course
Can't you just add another line with something like:
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname]) )
{
if ($fieldname != 'visible' || $_POST[$fieldname] != 0)
{
$errors [] = $fieldname;
}
}