How to Get PHP Array Length

PHP arrays are a strange breed. Unlike arrays in other programming languages, PHP's arrays are actually ordered maps. An ordered map is a data-type that associates keys, or indexes, with values. While maps are more computationally expensive than traditional arrays, they can be used as a number of other data-types including traditional arrays, lists, queues and stacks. Counting the number of elements in a PHP array is a common and straightforward task.

Instructions

    • 1

      Create an array using PHP's "$variable = array(item1, item2, ...)" syntax. For example:

      $my_array = array('Jones', 7, 'Steve', array('short', 'tall'), 5.6);

    • 2

      Use PHP's "count" function to get the number of elements in the array. The function accepts the array as a parameter and returns an integer with the number of elements. Here is an example:

      echo "The array has " . count($my_array) . " elements.";

    • 3

      If the array you wish to count is a multidimensional array, that is, it is an array that contains arrays, use the constant "COUNT_RECURSIVE" as the second parameter. Here is an example:

      echo "The array has " . count($my_array, COUNT_RECURSIVE) . " elements and sub-elements.";

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured