This question on 'How to tell if a PHP array is empty' had me thinking of this question
Is there a reason that count should be used instead of empty when determining if an array is empty or not?
My personal thought would be if the 2 are equivalent for the case of empty arrays you should use empty because it gives a boolean answer to a boolean question. From the question linked above, it seems that count($var) == 0 is the popular method. To me, while technically correct, makes no sense. E.g. Q: $var, are you empty? A: 7. Hmmm...
Is there a reason I should use count == 0 instead or just a matter of personal taste?
As pointed out by others in comments for a now deleted answer, count will have performance impacts for large arrays because it will have to count all elements, whereas empty can stop as soon as it knows it isn't empty. So, if they give the same results in this case, but count is potentially inefficient, why would we ever use count($var) == 0?
I generally use empty. Im not sure why people would use count really - If the array is large then count takes longer/has more overhead. If you simply need to know whether or not the array is empty then use empty.
I was curious to see which one was actually faster so I made a simple script to benchmark those functions.
<?php
function benchmark($name, $iterations, $action){
$time=microtime(true);
for($i=0;$i<=$iterations;++$i){
$action();
}
echo $name . ' ' . round(microtime(true)-$time, 6) . "\n";
}
$iterations = 1000000;
$x = array();
$y = range(0, 10000000);
$actions = array(
"Empty empty()" => function() use($x){
empty($x);
},
"Empty count()" => function() use($x){
count($x);
},
"Full empty()" => function() use($y){
empty($y);
},
"Full count()" => function() use($y){
count($y);
},
############
"IF empty empty()" => function() use($x){
if(empty($x)){ $t=1; }
},
"IF empty count()" => function() use($x){
if(count($x)){ $t=1; }
},
"IF full empty()" => function() use($y){
if(empty($y)){ $t=1; }
},
"IF full count()" => function() use($y){
if(count($y)){ $t=1; }
},
############
"OR empty empty()" => function() use($x){
empty($x) OR $t=1;
},
"OR empty count()" => function() use($x){
count($x) OR $t=1;
},
"OR full empty()" => function() use($y){
empty($y) OR $t=1;
},
"OR full count()" => function() use($y){
count($y) OR $t=1;
},
############
"IF/ELSE empty empty()" => function() use($x){
if(empty($x)){ $t=1; } else { $t=2; }
},
"IF/ELSE empty count()" => function() use($x){
if(count($x)){ $t=1; } else { $t=2; }
},
"IF/ELSE full empty()" => function() use($y){
if(empty($y)){ $t=1; } else { $t=2; }
},
"IF/ELSE full count()" => function() use($y){
if(count($y)){ $t=1; } else { $t=2; }
},
############
"( ? : ) empty empty()" => function() use($x){
$t = (empty($x) ? 1 : 2);
},
"( ? : ) empty count()" => function() use($x){
$t = (count($x) ? 1 : 2);
},
"( ? : ) full empty()" => function() use($y){
$t = (empty($y) ? 1 : 2);
},
"( ? : ) full count()" => function() use($y){
$t = (count($y) ? 1 : 2);
}
);
foreach($actions as $name => $action){
benchmark($name, $iterations, $action);
}
//END
Since I was doing it I also tried to check the performance doing operations that would normally be associated with count()/empty()
Using PHP 5.4.39:
Empty empty() 0.118691
Empty count() 0.218974
Full empty() 0.133747
Full count() 0.216424
IF empty empty() 0.166474
IF empty count() 0.235922
IF full empty() 0.120642
IF full count() 0.248273
OR empty empty() 0.123875
OR empty count() 0.258665
OR full empty() 0.157839
OR full count() 0.224869
IF/ELSE empty empty() 0.167004
IF/ELSE empty count() 0.263351
IF/ELSE full empty() 0.145794
IF/ELSE full count() 0.248425
( ? : ) empty empty() 0.169487
( ? : ) empty count() 0.265701
( ? : ) full empty() 0.149847
( ? : ) full count() 0.252891
Using HipHop VM 3.6.1 (dbg)
Empty empty() 0.210652
Empty count() 0.212123
Full empty() 0.206016
Full count() 0.204722
IF empty empty() 0.227852
IF empty count() 0.219821
IF full empty() 0.220823
IF full count() 0.221397
OR empty empty() 0.218813
OR empty count() 0.220105
OR full empty() 0.229118
OR full count() 0.221787
IF/ELSE empty empty() 0.221499
IF/ELSE empty count() 0.221274
IF/ELSE full empty() 0.221879
IF/ELSE full count() 0.228737
( ? : ) empty empty() 0.224143
( ? : ) empty count() 0.222459
( ? : ) full empty() 0.221606
( ? : ) full count() 0.231288
Conclusions if you're using PHP:
empty() is much much faster than count() in both scenarios, with an empty and populated array
count() performs the same with a full or empty array.
Doing a simple IF or just a Boolean operation is the same.
IF/ELSE is very slightly more efficient than ( ? : ). Unless you're doing billions of iterations with expressions in the middle it is completely insignificant.
Conclusions if you're using HHVM:
empty() is a teeny-weeny bit faster than count() but insignificantly so.
[ The rest is the same as in PHP ]
In conclusion of the conclusion, if you just need to know if the array is empty always use empty();
This was just a curious test simply done without taking many things into account. It is just a proof of concept and might not reflect operations in production.
I think it's only personal preference. Some people might say empty is faster (e.g. http://jamessocol.com/projects/count_vs_empty.php) while others might say count is better since it was originally made for arrays. empty is more general and can be applied to other types.
php.net gives the following warning for count though :
count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.
In other words, if the variable is not set, you will get a notice from PHP saying it's undefined. Therefore, before using count, it would be preferable to check the variable with isset. This is not necessary with empty.
Is there a reason that count should be used instead of empty when determining if an array is empty or not?
There is, when you need to do something on non-empty array knowing it's size:
if( 0 < ( $cnt = count($array) ) )
{
echo "Your array size is: $cnt";
}
else
echo "Too bad, your array is empty :(";
But I wouldn't recommend using count, unless you are 100% sure, that what you are counting is an array. Lately I have been debugging code, where on error function was returning FALSE instead of empty array, and what I discovered was:
var_dump(count(FALSE));
output:
int 1
So since then I am using empty or if(array() === $array) to be sure that I have array that is empty.
Alternatively, you can cast the variable as a boolean (implicitly or explicitly):
if( $value )
{
// array is not empty
}
if( (bool) $value )
{
// array is still not empty
}
This method does generate an E_NOTICE if the variable is not defined, similarly to count().
For more information, see the PHP Manual page on type comparisons.
count() seems to work better with array-like interfaces that implement ArrayAccess/Countable. empty() returns false for these kinds of objects even if they have no elements. Typically these classes will implement the Countable interface, so if the question is "Does this collection contain elements?" without making an assumption about the implementation, then count() is a better option.
There is no strong reason to prefer count($myArray) == 0 over empty($myArray). They have identical semantics. Some might find one more readable than the other. One might perform marginally better than the other but it's not likely to be a significant factor in the vast majority of php applications. For all practical purposes, the choice is a matter of taste.
My personal preference is more for coding elegance (in relation to my specific use-case). I agree with Dan McG inasmuch that count() isn't responding with the correct datatype (in this case boolean) for the test in question forcing the developer to write more code to fill an 'if' statement.
Whether this has any significant impact on performance is only debatable for extremely large arrays (which you probably won't have enough memory allocation for anyway in most setups).
Particularly when it comes to PHP's $_POST array, it seems much more "logical" in my opinion to write/see:
if ( !empty ( $_POST ) ) {
// deal with postdata
}
Hope this might help someone even though it has already been answered (and debated some what). In my own scenario, I know all my arrays all have 7 elements (checks were made earlier in my code) and I am performing an array_diff which of course returns an array of zero when equal.
I had 34 sec for count and 17 sec for empty. Both give me the same calculations so my code is still fine.
However you can also try the == or === as in PHP - Check if two arrays are equal. The best I would say is try count vs empty vs == empty array, then see which gives your own best perfs. In my case count was the slowest so I am using empty now... will be checking serialize next
Sometimes using empty is a must. For example this code:
$myarray = array();
echo "myarray:"; var_dump($myarray); echo "<br>";
echo "case1 count: ".count($myarray)."<br>";
echo "case1 empty: ".empty($myarray)."<br>";
$glob = glob('sdfsdfdsf.txt');
echo "glob:"; var_dump($glob); echo "<br>";
echo "case2 count: ".count($glob)."<br>";
echo "case2 empty: ".empty($glob);
If you run this code like this: http://phpfiddle.org/main/code/g9x-uwi
You get this output:
myarray:array(0) { }
case1 count: 0
case1 empty: 1
glob:bool(false)
case2 count: 1
case2 empty: 1
So if you count the empty glob output you get wrong output. You should check for emptiness.
From glob documentation:
Returns an array containing the matched files/directories, an empty
array if no file matched or FALSE on error.
Note: On some systems it
is impossible to distinguish between empty match and an error.
Also check this question:
Why count(false) return 1?
Since a variable parsed as negative would return int(1) with count()
I prefer ($array === [] || !$array) to test for an empty array.
Yes, we should expect an empty array, but we shouldn't expect a good implementation on functions without enforced return types.
Examples with count()
var_dump(count(0));
> int(1)
var_dump(count(false));
> int(1)
I remade my mind guys, thanks.
Ok, there is no difference between the usage of empty and count. Technically, count should be used for arrays, and empty could be used for arrays as well as strings. So in most cases, they are interchangeable and if you see the php docs, you will see the suggestion list of count if you are at empty and vice versa.
Related
Example: I'm checking for the existence of an array element like this:
if (!self::$instances[$instanceKey]) {
$instances[$instanceKey] = $theInstance;
}
However, I keep getting this error:
Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16
Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?
You can use either the language construct isset, or the function array_key_exists.
isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset :
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
boolean true
While the second one will get you (the element exists, but is null) :
boolean false
And the last one will get you (the element doesn't exist) :
boolean false
On the other hand, using array_key_exists like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'd get those outputs :
boolean true
boolean true
boolean false
Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.
For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}
array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.
It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)
if (isset($a['element']) || array_key_exists('element', $a)) {
//the element exists in the array. write your code here.
}
The benchmarking comparison: (extracted from below blog posts).
array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms
See
http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/
and
http://thinkofdev.com/php-isset-and-multi-dimentional-array/
for detailed discussion.
You can use the function array_key_exists to do that.
For example,
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
PS : Example taken from here.
You can use isset() for this very thing.
$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
According to the PHP manual you can do this in two ways. It depends what you need to check.
If you want to check if the given key or index exists in the array use array_key_exists
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
If you want to check if a value exists in an array use in_array
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>
You want to use the array_key_exists function.
A little anecdote to illustrate the use of array_key_exists.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
You can also use array_keys for number of occurrences
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>
For validating a variable value we can do
if(empty($var)){
}
OR
This will return true on empty string, 0 as number, false, null
if(!$var){
}
What is the difference between this two approaches, are them equivalent?
EDIT: Some examples where they behave different will be more pratical.
EDIT2: The only difference founded from answers is that the second will throw a notice if $var is undefined. What about the boolean value they return?
EDIT3: for $var I mean any variable with any value, or even an undefined variable.
Conclusion from users answers:
if(!$var) and empty($var) are equivalent as described here http://php.net/manual/en/types.comparisons.php, they will return the same bool value on the same variable.
if(!$var) will return a php notice if $var is not defined, normally this is not the case (if we write good code) most IDEs will underline it.
When checking simple variables if(!$var) should be ok
When checking arrays index ($var['key']) or object properties ($var->key)
empty($var['key']) is better using empty.
the problem is that since !$vars is shorter than empty($vars) many of us will prefer the first way
You prefer the first one because it is a "shorter way"?
Shorter code does not mean better code, or faster scripts ;)
The speed of PHP functions and its various other behaviours is not determined by the length of the function name. It is determined by what PHP is actually doing to evaluate, action, and return results.
Besides that, don't choose methods based on length of code, choose methods based on scenario and best approach "for a given scenario".
Which is best depends on what you need, and there are other variable checks other than the two you mentioned (isset() for one).
but the problem is are they equivalent always
Not necessarily - see
http://php.net/manual/en/types.comparisons.php
Or create a quick test script to see what PHP returns for your two scenarios.
You could also be initialising your variables in your framework (or, likely, stand alone script), which means the scenario changes, as could your question and approach you use.
It's all contextual as to which is the best.
As for the required answer.
Anyway, to answer your question, here are some tests:
(!$vars)
Example code:
if ( !$vars )
{
echo "TRUE";
}
else
{
echo "FALSE";
}
will return:
Notice: Undefined variable: vars in /whatever/ on line X
TRUE
However, if you initialise the var in your scripts somewhere first:
$vars = "";
$vars = NULL;
$vars = 0;
Any of the above will return:
[no PHP notice]
TRUE
$vars = "anything";
will return:
FALSE
This is because with the exclamation mark you are testing if the var is FALSE, so when not initialised with a string the test script returns TRUE because it is NOT FALSE.
When we initialise it with a string then the var NOT being FALSE is FALSE.
empty($vars)
Example code:
if ( empty($vars) )
{
echo "TRUE";
}
else
{
echo "FALSE";
}
Not initialised/set at all, and all of the following:
$vars = "";
$vars = NULL;
$vars = 0;
will return:
TRUE
There is no PHP notice for using empty, so here we show a difference between the two options (and remember when I said the shortest code is not necessarily the "best"? Depends on the scenario etc.).
And as with the previous test:
$vars = "anything";
returns:
FALSE
This is the same with ( !$var ), you are testing IF EMPTY, and without the var being initialised at all, or with any "empty()" value: eg (""), or NULL, or zero (0), then testing if the var is empty is TRUE, so we get TRUE output.
You get FALSE when setting the var to a string because IS EMPTY = FALSE as we set it to something.
The difference is empty() does not throw a PHP notice when var is not defined, whereas (!$var) will.
Also, you may prefer it for being "shorter code", but if (!$var) isn't really much shorter/better looking than the widely used if (empty($var)).
But again, this depends on the scenario - PHP provides different options to suit different requirements.
No they are not equal
if(empty($var)){
echo "empty used\n";
}
if(!$var){ # line no. 6
echo "! used";
}
will output
empty used
Notice: Undefined variable: var in /var/www/html/test.php on line 6
! used
Following values are considered to be empty when using empty() function
"" (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)
As you can read in empty docs
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
They are not.
The first one verify if $var has any value.
The second one verify as boolean - if true or not.
The second one will give you a notice, the first one will be true if the value is empty for $var.
If you wish to verify if $var exists, use isset.
if( !isset($var) )
echo '$var does not exists!<br>';
if(empty($var))
echo 'The value is empty or does not exists!<br>';
if( !$var )
echo 'Value is false!<br>';
$var = '';
if(empty($var))
echo 'The value is empty or does not exists!<br>';
Use this to view the notice
error_reporting(-1);
ini_set('display_errors', 1);
The main difference is that empty() will not complain if the variable does not exist, whereas using ! will generate a warning.
In older versions of PHP, empty() only worked on direct variables, meaning this would fail:
empty($a && $b);
This has been changed in 5.5
The official manual contains all you have to know on this subject:
http://php.net/manual/en/types.comparisons.php
if (!$var) is the last column, boolean : if($x) negated.
As you can see they are the same, but empty won't complain if the variable wasn't set.
From the manual:
empty() does not generate a warning if the variable does not exist
Take some time, and study that chart.
As far as I know, it's pretty simple.
empty() is basically equivalent to !isset($var) || !$var and does not throw any warnings/notices, whereas using just !$var will throw a notice if the variable isn't defined.
For the sake of completeness, the following are considered empty when using empty():
empty strings
empty arrays
0, 0.0, '0' (int, float, string)
null
false
defined variables without a value
From a boolean value return empty is equivaliend to !:
empty($var) === !$var; // supposed that $vars has been defined here
From a notice/waning notification they are not equivalent:
empty($array['somekey']); //will be silent if somekey does not exists
!$array['somekey']; // will through a warning if somekey does not exists
Ok... right of the batt, let me clear what the question is not about.
it is not about in_array.
Because as the PHP manual clearly explains, the function 'in_array' checks if a value exists in an array. But it does this check based on equality. It does not do as based on partial existence.
For example, if the value I'm looking is 'overflow' and I happened have an array like this
array('cnn','stackoverflow'),
the in_array would come back with a FALSE, telling me that overflow does not exist in the in values of this array, which in a way is TRUE. but also in a way, is FALSE.
To me, the string "overflow" do exists in the string stackoverflow". Therefore, it should have returned TRUE. Of course I cannot argue this point much.
Is there another function ( or an efficient one-liner) in PHP to get me what I want?
i'm looking for a solution something like this
array_filter($ary,'strlen');
which removes the empty lines from the $ary in a very efficient way.
I do not want to go thru the traditional way that is to go thru a foreach and do a comparison between the needle and the haystack using strpos. That solution I already know.
I'm looking for a one liner, like in the (strlen) example
Thx.
No function available in php which satisfy exact requirement of author. Developer has to write some code so you can try below code:
function array_check($arr, $keyword) {
foreach($arr as $index => $string) {
if (strpos($string, $keyword) !== FALSE)
return $index;
}
}
var_dump(array_check(array('cnn','stackoverflow'),'overflow'));
exit;
Lame option: false !== strpos(implode($ary, '|'),'overflow') As long as the separator character (| here) isn't in your search string, this works.
More sophisticated option: count(array_filter( $ary, function($x) { return strpos($x, 'overflow'); } ) );
Edit: Second option full code looks like this:
$ary = array('cnn', 'stackoverflow'); // or whatever your data is
(bool) count(array_filter( $ary, function($x) { return strpos($x, 'overflow'); } ) );
The count() value will be 0 if not found, or positive if a match was found. So, you could use it in an if() statement, return it from a function, or whatever.
I have an array with numerous dimensions, and I want to test for the existence of a cell.
The below cascaded approach, will be for sure a safe way to do it:
if (array_key_exists($arr, 'dim1Key'))
if (array_key_exists($arr['dim1Key'], 'dim2Key'))
if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))
echo "cell exists";
But is there a simpler way?
I'll go into more details about this:
Can I perform this check in one single statement?
Do I have to use array_key_exist or can I use something like isset? When do I use each and why?
isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like
isset($arr[1][2][3])
is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).
However, if you have
$arr['a'] = null;
then
isset($arr['a']); // false
array_key_exists('a', $arr); // true
comment followup:
Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:
isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.
function recursiveIsset($variable, $checkArray, $i=0) {
$new_var = null;
if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable[$checkArray[$i]];
else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable->$checkArray[$i];
if(!isset($new_var))
return false;
else if(count($checkArray) > $i + 1)
return recursiveIsset($new_var, $checkArray, $i+1);
else
return $new_var;
}
Use: For instance
recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))
In my case in drupal this ment for me that the following variable existed
$variables['content']['body']['#object']->body['und']
due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed
$variables->content->body['#object']->body['und']
For a fast one liner you can use has method from this array library:
Arr::has('dim1Key.dim2Key.dim3Key')
Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.
Also, this method will work as expected for null value because it internally uses array_key_exists.
If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.
So yes, there is a simpler way using one single if statement like the following:
if (isset($arr['dim1Key']['dim2Key']) &&
array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
I prefer creating a helper function like the following:
function my_isset_multi( $arr,$keys ){
foreach( $keys as $key ){
if( !isset( $arr[$key] ) ){
return false;
}
$arr = $arr[$key];
}
return $arr;
}
Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.
Imagine you have this kind of array:
$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );
You can write something like this:
$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );
if( $arr ){
//You can use the variable $arr without problems
}
The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.
Example: I'm checking for the existence of an array element like this:
if (!self::$instances[$instanceKey]) {
$instances[$instanceKey] = $theInstance;
}
However, I keep getting this error:
Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16
Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?
You can use either the language construct isset, or the function array_key_exists.
isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on isset :
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
The first one will get you (the element exists, and is not null) :
boolean true
While the second one will get you (the element exists, but is null) :
boolean false
And the last one will get you (the element doesn't exist) :
boolean false
On the other hand, using array_key_exists like this :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'd get those outputs :
boolean true
boolean true
boolean false
Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.
For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)
For instance, your code could become something like this :
if (!isset(self::$instances[$instanceKey])) {
$instances[$instanceKey] = $theInstance;
}
array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.
It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)
if (isset($a['element']) || array_key_exists('element', $a)) {
//the element exists in the array. write your code here.
}
The benchmarking comparison: (extracted from below blog posts).
array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms
See
http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/
and
http://thinkofdev.com/php-isset-and-multi-dimentional-array/
for detailed discussion.
You can use the function array_key_exists to do that.
For example,
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
PS : Example taken from here.
You can use isset() for this very thing.
$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
According to the PHP manual you can do this in two ways. It depends what you need to check.
If you want to check if the given key or index exists in the array use array_key_exists
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
If you want to check if a value exists in an array use in_array
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>
You want to use the array_key_exists function.
A little anecdote to illustrate the use of array_key_exists.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
You can also use array_keys for number of occurrences
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>