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
}
Related
i have this array:
include("config.php");
$start = "2014-06-20 08:00:00";
$data = mysql_query ("select * from evenement WHERE start = '$start'");
$zaznam = mysql_fetch_array ($data);
while($zaznam = mysql_fetch_array ($data))
{
$arr2[] = $zaznam["resourceId"]; //store query values in second array
}
If i echo $arr2 i get this:
Array ( [0] => STK1 )
now i make condition for array_search:
if (array_search('STK1', $arr2)) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
but i get this Arr2 not contains STK1
how it is possible? What im doing wrong?
That is totally correct behaviour for PHP.
The documention for the return value says:
Returns the key for needle if it is found in the array, FALSE otherwise.
In your case you are getting 0 which also evaluates to false in an if.
You have to check if the value is not false using the !== operator.
if (array_search('STK1', $arr2) !== false) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
From the array_search documentation:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
array_search is returning 0 because it found a match at index 0 of the array. This is evaluating to false.
Instead try:
if (array_search('STK1', $arr2) !== false) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
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've got a function that is used in a loop, however it is not working at all, here's example of my code
function is_banned_category($a) {
if(!is_array($a)) {
echo "returning false <Br/>";
return false;
}
$banned_list = array(
'Shopping',
'Product Info'
);
foreach($a as $cat) {
if(array_search($cat,$banned_list)) {
$return = true;
} else {
echo "Not found in:'{$cat}' <br/>";
}
}
return $return;
}
$a = array('Shopping');
if(is_banned_category($a)) {
echo "Item will not be added as it's in banned category";
}
Which would produce:
Item will not be added as it's in banned category
Am I missing something obvious here? It works with "Product Info" but not "Shopping"?
array_search($cat,$banned_list) returns 0, witch causes expression to evaluate to false. use in_array() or evaluate using Identical Operator ===
array_search returns the key of array value if exist, so in your case
array key of Shopping is "0"
if(array_search($cat,$banned_list)) // return 0
So else part will be worked
The function array_search will return the index of the occurrence if found (which could be 0, which evaluates to false), or else false if not found, so you must use
if(array_search($cat, $banned_list) !== false) {
[.. do your stuff .. ]
}
to perform the check, or else you could do
if(in_array($cat, $banned_list)) {
[.. do your stuff .. ]
}
which, IMHO, is a little bit cleaner.
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 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
}