Testing an array for an empty string and returning an int (0 or 1) - best practice
What I started with:
foreach($a as $b){if($b=='')return 0;}return 1; // works but verbose
My second attempt:
return (in_array('',$a)+0); // returns the opposite of what I need
What I am currently using:
return in_array('',$a)?'0':'1';
using a cast per JRL (shortest)
return (int)!in_array('',$a);
I assume this is the best way to do this, but just wanted to validate. Is this the best way to test for an empty value in an array?
I am aware that this tests for 0,NULL,FALSE or an 开发者_C百科empty string and that is O.K.
Here's a modification of your second statement that should work. Just negate the return value of in_array:
return !in_array('',$a);
Other alternative:
return (int)!in_array('', $a));
Your proposal to check an array $a
for strings cannot be written shorter than:
return in_array('', $a)?0:1;
If you want to see the difference between 0, NULL, FALSE, or an empty string, add a third parameter to the in_array
function. This parameter will force the function to also take the type of the element into account. In other words, it compares using ===
instead of ==
.
return in_array('', $a, TRUE)?0:1; //Empty string
return in_array(0, $a, TRUE)?0:1; //Zero
return in_array(NULL, $a, TRUE)?0:1; //NULL
return in_array(FALSE, $a, TRUE)?0:1;//FALSE
See also: http://www.php.net/manual/en/function.in-array.php
First one isn't correct.
Second one isn't correct
Third one is perfect for your case
OT: Trying to codegolf?
I think as far as best practice goes, just plain !in_array('', $a)
is the way to go.
There's (generally speaking) no good reason to cast it to an int. Type juggling in PHP works very well. It isn't the PHP way to do casts like this.
精彩评论