You can use count(), along with your knowledge of for loops and working with array elements, to loop through all the elements in an indexed array:

<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Alfred Hitchcock, Stanley Kubrick, Martin Scorsese, Fritz Lang":

$totalElements = count( $directors );

for ( $i=0; $i < $totalElements; $i++ ) {
echo $directors[$i];
if ( $i < $totalElements -1 ) echo ", ";
}

?>

The above code first reads the total number of array elements using count(), and stores the result (4) in$totalElements. It then loops through each element index, from 0 through to $totalElements - 1 (i.e. 3), displaying the element’s value as it goes. (The if statement displays a comma and space after each element except for the last.)
You do need to be bit careful when using count() with for. As you saw in Above, PHP doesn’t distinguish between indexed and associative arrays, and numeric array indices don’t have to be contiguous either. Consider the following example:
<?php

error_reporting(0);
ini_set( 'display_errors', true );

$directors = array( 0 => "Alfred Hitchcock", 1 => "Stanley Kubrick", 2 => "Martin Scorsese", 39 => "Fritz Lang" );

// Displays "Alfred Hitchcock, Stanley Kubrick, Martin Scorsese,"
// and generates an "Undefined offset: 3" notice:

$totalElements = count( $directors );

for ( $i=0; $i < $totalElements; $i++ ) {
echo $directors[$i];
if ( $i < $totalElements -1 ) echo ", ";
}

?>

What’s happening here? The above example is identical to the one before, except that the array indices are no longer contiguous (0, 1, 2, and 39). We’ve also set PHP to display all errors in the browser. When the code tries to read the element with the index of 3, PHP generates an “Undefined offset” notice because an element with this index doesn’t exist.
The lesson here is that count() - 1 only equals the index of the last element in the array when the array indices are contiguously numbered (for example, 0, 1, 2 and 3). Fortunately, this is usually the case with indexed arrays.
If you’re not sure whether the indices of an array are contiguous, you can use other PHP constructs such as foreach to loop through the array’s elements. (More on foreach in a later tutorial.)

0 comments:

Post a Comment

 
Top
Blogger Template