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"
Related
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.
I have a question, how do I put a condition for a function that returns true or false, if I am sure that the array is empty, but isset() passed it.
$arr = array();
if (isset($arr)) {
return true;
} else {
return false;
}
In this form returns bool(true) and var_dump shows array (0) {}.
If it's an array, you can just use if or just the logical expression. An empty array evaluates to FALSE, any other array to TRUE (Demo):
$arr = array();
echo "The array is ", $arr ? 'full' : 'empty', ".\n";
Sometimes it is suggested instead of just if'ing the array variable like:
if (!$array) {
// empty
}
to write out:
if (empty($array)) {
// empty
}
for readability reasons. Compare empty(php) language construct.
The PHP manually nicely lists what is false and not.
Use PHP's empty() function. It returns true if there are no elements in the array.
http://php.net/manual/en/function.empty.php
Use empty() to check for empty arrays.
if (empty($arr)) {
// it's empty
} else {
// it's not empty
}
You can also check to see how many elements are in the array via the count function:
$arr = array();
if (count($arr) == 0) {
echo "The array is empty!\n";
} else {
echo "The array is not empty! It has " . count($arr) . " elements!\n";
}
use the empty property as
if (!empty($arr)) {
//do what u want if its not empty
} else {
//do what if its empty
}
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 was wondering how can I check if an array is empty or not in a function
Here is part of my code.
if (!mysqli_query($dbc, $sql)) {
trigger_error(mysqli_error($dbc));
return;
} else {
$t = array();
while($row = mysqli_fetch_array($result)) {
$t[] = $row[0];
}
}
if($tr > 0){
$ts = array_sum($t);
}
Use the empty() function:
http://php.net/manual/en/function.empty.php
Loose equivalency checking returns false on an empty array
if(array()) // returns false
http://php.net/manual/en/types.comparisons.php
Use count() to count the number of elements in the array.
An easy method would be to use the count function.
For example:
if(count($sourceArray) != 0) {
// Do exciting things here...
}
empty($t);
gives you true if $t is considered empty.
To check if array is empty:
if (sizeof($arr) == 0)
{
//Empty array
}
To check whether an element exists in an array or not:
if (in_array($element, $arr))
{
//Element found in the array
}