Using PHP 8.3, while attempting to determine the number of elements in an array via the PHP count() function, the following error message occurred.
Fatal error: Uncaught TypeError: count() …
As an example, the following $test array is provided.
$test = array(‘red’, ‘green’, ‘blue’, ‘orange’);
Attempt to determine an integer value representing the number of elements in $test via the count() function as follows.
$elements = count($test);
The result of said attempt is the aforementioned fatal error.
As an aside, it is interesting that the run code boxes on the PHP.net website produce the same fatal error, but the run code boxes – the ones tried today – on the W3schools website do not produce an error, presumably because the W3schools’ code boxes employ an older version of PHP.
Regarding attempting to determine the number of elements, represented as an integer, in the $test array, the following code was also unsuccessful.
$elements = intval( count($test) );
The failure seems to be the same issue as without intval() function. Specifically, the $test array must, in one way of accomplishing the task, somehow be made to be of type Countable.
Alternatively, is it an acceptable best practice to simply loop through test and count the elements? If the loop-and-count method is an accepted best practice, what is used for the limit of the loop, and does it matter if some elements are blank (i.e., “”) elements? Your thoughtful replies would be appreciated.