note 124902 added to function.count

From: Date: Sun, 12 Apr 2020 14:54:03 +0000
Subject: note 124902 added to function.count
Groups: php.notes 
Request: Send a blank email to php-notes+get-214459@lists.php.net to get a copy of this message
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(). ---- Server IP: 45.112.84.4 Probable Submitter: 38.142.137.34 (proxied: 96.61.135.240) ---- Manual Page -- http://php.net/manual/en/function.count.php Edit -- https://master.php.net/note/edit/124902 Del: integrated -- https://master.php.net/note/delete/124902/integrated Del: useless -- https://master.php.net/note/delete/124902/useless Del: bad code -- https://master.php.net/note/delete/124902/bad+code Del: spam -- https://master.php.net/note/delete/124902/spam Del: non-english -- https://master.php.net/note/delete/124902/non-english Del: in docs -- https://master.php.net/note/delete/124902/in+docs Del: other reasons-- https://master.php.net/note/delete/124902 Reject -- https://master.php.net/note/reject/124902 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#214459) next »