note 113617 added to function.count
| From: | MaxTheDragon at home dot nl | Date: | Wed, 06 Nov 2013 13:21:34 +0000 |
| Subject: | note 113617 added to function.count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-197443@lists.php.net to get a copy of this message | ||
If you wish to test if an array contains any elements (or is empty), you might tempted to use count
to do something like this:
<?php
if (count($my_array) > 0) {
// array is not empty...
}
// or this ...
if (count($my_array) === 0) {
// array is empty...
}
?>
Using the count function here is totally unnecessary and slower.
Instead, you should rely on the fact that empty arrays evaluate to false when cast to a boolean:
<?php
$hasElements = (boolean) $my_array;
// or ...
$isEmpty = !$my_array;
// or in a conditional statement...
if ($my_array) {
// array is not empty...
}
?>
Only use count if you need to know if an array contains a specific number of elements n (where n
> 0).
----
Server IP: 192.41.45.150
Probable Submitter: 217.171.229.15
----
Manual Page -- http://php.net/manual/en/function.count.php
Edit -- https://master.php.net/note/edit/113617
Del: integrated -- https://master.php.net/note/delete/113617/integrated
Del: useless -- https://master.php.net/note/delete/113617/useless
Del: bad code -- https://master.php.net/note/delete/113617/bad+code
Del: spam -- https://master.php.net/note/delete/113617/spam
Del: non-english -- https://master.php.net/note/delete/113617/non-english
Del: in docs -- https://master.php.net/note/delete/113617/in+docs
Del: other reasons-- https://master.php.net/note/delete/113617
Reject -- https://master.php.net/note/reject/113617
Search -- https://master.php.net/manage/user-notes.php