note 124902 deleted from function.count by cmb
| From: | cmb@php.net | Date: | Sun, 12 Apr 2020 15:38:30 +0000 |
| Subject: | note 124902 deleted from function.count by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214461@lists.php.net to get a copy of this message | ||
Note Submitter: rnealxp at yahoo dot com
----
In PHP 7.3+ we have the new function array_key_last(). Usage of this function to (pre-)identify the
last key of a numerically indexed array is faster than using function <?php count($arr)-1 ?>
to identify the key. One pitfall to watch out for is that if array_key_last() is supplied an empty
array, it will return NULL. Remembering to check for this while maintaining a code-base dangerous
and would therefore justify a wrapper function.
<?php
function get_el_count_numerically_indexed_array(array $arr):int{
return (array_key_last($arr) ?? 0);
}
?>
Agreed, the wrapper may be too costly to some.
Where existed:
<?php (count($arr)-1) ?>
You would begin using:
<?php (array_key_last($arr) ?? 0) ?>
If you do not know ahead of time that the array is numerically indexed, and that it could possibly
be associative...safer/faster to stick with count().