Home and Learn: PHP Programming Course


The PHP count function

 

The count( ) function is useful when you want to return how many elements are in your array. You can then use this in a for loop. Here's an example we used earlier, only this time with the count function:

$seasons = array("Autumn", "Winter", "Spring", "Summer");

$array_count = count($seasons);

for ($key_Number = 0; $key_Number < $array_count; $key_Number++) {

print $seasons[$key_Number];

}

To get how many elements are in the array, we used this:

$array_count = count($seasons);

So you type the word count and then the round brackets. In between the round brackets, you type the name of your array. The function then counts how many elements are in the array, which we then assign to a variable called $array_count. You can then use this value as the end condition in you loop:

for ($key_Number = 0; $key_Number < $array_count; $key_Number++)

Here, we're saying, "keep looping round as long as the value in $key_Number is less than the value in $array_count.

To round off this section on arrays, there are some script for you to try out in the next part.

<-- Back One Page | Move on to the Next Part -->

Back to the PHP Contents Page

 

Email us: enquiry at homeandlearn.co.uk