Number of Elements of Array

Number of elements of array is very usual, which can be used as control for the loop or other purposes. Function to get it in JavaScript is varArray.length. In PHP it is count($ varArray) or sizeof($ varArray). Since sizeof() is just an alias of count(), it is suggested using count(), since sizeof() has other meaning in other languages.

The problem happens when array is undefined/not exist. In JavaScript .length would generate a fatal error. So, for save play, it is suggested always using follow codes:

var len = 0;
if ('undefined'!=typeof(varArray)) len = varArray.length;

In PHP count() would generate a return value of 0 together with a non-fatal error message, which would cause even more serious problem because of its non-fatal nature. Fortunately, PHP provides an easy non-fatal error message suppress method “@”:

@count($varArray);

It is very useful because it enables you to always associate @ with count(). And please do so.

For multidimensional array, the usage will be exactly same; and can be used for particular dimension, such as varArray[i] or $varArray[i].

No comments:

Post a Comment

Labels