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)
Related
I want to compare the session[name] to all the even instances of text.
For example:
$_SESSION['name'] === $text[1] or $text[2] or $text[4] or $text[6]
The problem with doing it like the way above is that the code above will limit to only 6. Is there any way to just say "compare this to all the even instances of '$text' "?
Basically what I'm trying to do is say:
Compare $_SESSION['name'] to all even info from the $Text array.
So for example if this was my array:
$text = array("info0", "info1", "info2", "info3")
I would want to compare something to all the even info instances in the array(ie: info0, info2)
The code:
//compare the strings
if ($_SESSION['name'] === $text[0] && $_SESSION['pass'] == $text[1]) {
//echo "That is the correct log-in information";
header("Location: home.php");
} else {
echo "That is not the correct log-in information.";
}
XaxD's answer is good, and probably what you are interested in, but if you are using an associative array and want to look at every other element of the array this will work:
function checkEvenValues($text)
{
$skip = array(true, false);
// set $iskp to 0 if you want the first element to be counted as even; else, set it to 1
$iskp = 0;
foreach ($text as $idx=>$val)
{
$skp = 1 - $skp;
if ($skip[$iskp]) continue;
if($_SESSION['name'] == $text[$i]) return (true);
}
return (false);
}
function checkEvenValues($text)
{
if($_SESSION['name'] === $text[1]) return true;
for($i = 2; $i < count($text); $i += 2)
{
if($_SESSION['name'] === $text[$i])
return true;
}
}
Presuming that your keys are the same as the numbers in your values ([0] => 'info0') etc, you can use something like this combining some PHP array functions to filter down to only even keys (including 1), then a strict in_array() check to determine if it's there:
function compareEvens($text, $compare) {
// swap keys for values (back again)
$evens = array_flip(
// apply custom filter function
array_filter(
// swap keys for values
array_flip($text),
// return if its even OR its one
function($key) {
return $key % 2 === 0 || $key === 1;
}
)
);
return in_array($compare, $evens, true);
}
Example:
$text = array("info0", "info1", "info2", "info3");
var_dump(compareEvens($text, 'info2')); // true
var_dump(compareEvens($text, 'info3')); // false
Docs:
array_flip()
array_filter()
in_array()
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 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
}
Without having to change the function signature, I'd like a PHP function to behave differently if given an associated array instead of a regular array.
Note: You can assume arrays are homogenous. E.g., array(1,2,"foo" => "bar") is not accepted and can be ignored.
function my_func(Array $foo){
if (…) {
echo "Found associated array";
}
else {
echo "Found regular array";
}
}
my_func(array("foo" => "bar", "hello" => "world"));
# => "Found associated array"
my_func(array(1,2,3,4));
# => "Found regular array"
Is this possible with PHP?
Just check the type of any key:
function is_associative(array $a) {
return is_string(key($a));
}
$a = array(1 => 0);
$a2 = array("a" => 0);
var_dump(is_associative($a)); //false
var_dump(is_associative($a2)); //true
You COULD use a check with array_values if your arrays are small and you don't care about the overhead (if they are large, this will be quite expensive as it requires copying the entire array just for the check, then disposing of it):
if ($array === array_values($array)) {}
If you care about memory, you could do:
function isAssociative(array $array) {
$c = count($array);
for ($i = 0; $i < $c; $i++) {
if (!isset($array[$i])) {
return true;
}
}
return false;
}
Note that this will be fairly slow, since it involves iteration, but it should be much more memory efficient since it doesn't require any copying of the array.
Edit: Considering your homogenious requirement, you can simply do this:
if (isset($array[0])) {
// Non-Associative
} else {
// Associative
}
But note that numerics are valid keys for an associative array. I assume you're talking about an associative array with string keys (which is what the above if will handle)...
Assuming $foo is homogeneous, just check the type of one key and that's it.
<?php
function my_func(array $foo) {
if (!is_int(key($foo))) {
echo 'Found associative array';
} else {
echo 'Found indexed array';
}
}
?>
In the light of your comment Assume arrays are homogenous; no mixtures.:
Just check if first (or last, or random) key is an integer or a string.
This would be one way of doing it, by checking if there's any keys consisting of non-numeric values:
function my_func($arr) {
$keys = array_keys($arr); // pull out all the keys into a new array
$non_numeric = preg_grep('/\D/', $keys); // find any keys containing non-digits
if (count($non_numeric) > 0) {
return TRUE; // at least one non-numeric key, so it's not a "straight" array
} else {
return FALSE: // all keys are numeric, so most likely a straight array
}
}
function is_associative($array) {
return count(array_keys($array)) != array_filter(array_keys($array), 'is_numeric');
}
Is it possible to use array_map() to test values of an array? I want to make sure that all elements of an array are numeric.
I've tried both
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( array_map("is_numeric", $arr) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
and
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( ( array_map("is_numeric", $arr) ) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
And for both I get
TRUE
TRUE
Can this be done? If so, what am I doing wrong?
Note: I am aware that I can get my desired functionality from a foreach loop.
array_map returns an array. So it will always be considered 'true'. Now, if you array_search for FALSE, you might be able to get the desire effects.
From the PHP.net Page
array_map() returns an array containing all the elements of
arr1 after applying the callback function to each one.
This means that currently you have an array that contains true or false for each element. You would need to use array_search(false,$array) to find out if there are any false values.
I'm usually a big advocate of array_map(), array_filter(), etc., but in this case foreach() is going to be the best choice. The reason is that with array_map() and others it will go through the entire array no matter what. But for your purposes you only need to go through the array until you run into a value for which is_numeric() returns false, and as far as I know there's no way in PHP to break out of those methods.
In other words, if you have 1,000 items in your array and the 5th one isn't numeric, using array_map() will still check the remaining 995 values even though you already know the array doesn't pass your test. But if you use a foreach() instead and have it break on is_numeric() == false, then you'll only need to check those first five elements.
You could use filter, but it ends up with a horrible bit of code
$isAllNumeric = count(array_filter($arr, "is_numeric")) === count($arr)
Using a custom function makes it a bit better, but still not perfect
$isAllNumeric = count(array_filter($arr, function($x){return !is_numeric($x);})) === 0
But if you were using custom functions array_reduce would work, but it still has some failings.
$isAllNumeric = array_reduce($arr,
function($x, $y){ return $x && is_numeric($y); },
true);
The failings are that it won't break when it has found what it wants, so the functional suggestions above are not very efficient. You would need to write a function like this:
function array_find(array $array, $callback){
foreach ($array as $x){ //using iteration as PHP fails at recursion
if ( call_user_func($callback, array($x)) ){
return $x;
}
}
return false;
}
And use it like so
$isAllNumeric = array_find($arr, function($x){return !is_numeric($x);})) !== false;
i have two tiny but extremely useful functions in my "standard library"
function any($ary, $func) {
foreach($ary as $val)
if(call_user_func($func, $val)) return true;
return false;
}
function all($ary, $func) {
foreach($ary as $val)
if(!call_user_func($func, $val)) return false;
return true;
}
in your example
foreach ( $arrays as $arr )
echo all($arr, 'is_numeric') ? "ok" : "not ok";
A more elegant approach IMHO:
foreach ($arrays as $array)
{
if (array_product(array_map('is_numeric', $array)) == true)
{
echo "TRUE\n";
}
else
{
echo "FALSE\n";
}
}
This will return true if all the values are numeric and false if any of the values is not numeric.