Oct
10
2008

ZCE Arrays: Array Iteration

Output Arrays

You can use the simple way, if you know what the index of the value you want to output such as:

echo $Beatles[2]; //outputs George

OR, we can use a loop to output every beetle:

foreach ($Beatles as $Beatle){
 echo "$Beatle";
}


Instead of using the foreach loop to output an arrays contents you can also use List to receive data from arrays. (The list function in PHP is also useful when outputting data from database).

while ( list( $art, $artist ) = each( $Beatle ) )
 echo "$artist is a $art";

This will output for example “Ringo is a Drummer” if using associative array or if you use enumerative array it may output something like “Ringo is a 3″.

Output Arrays - Testing

Well, we can use echo or print and this will output the element in the array. We can output the element to a variable. This is all great but when testing or debuggins a script we can use other stuff:
var_dump() and print_r.

var_dump(); Will output the elements value it will also output the elements data type, length and the array structure. Var_dump also works with ordinary variables as it will output their value and datatype.

var_dump($Beatles);

Will Output
array(4) {
[0]=>
string(4) “John”
[1]=>
string(4) “Paul”
[2]=>
string(6) “George”
[3]=>
string(5) “Ringo”
}
As you can see it shows lots of information, in the first line it shows how many elements their are, it shows the index of each element followed by the datatype and length. Var_dump has little use on finished projects and is mainly used for testing.

print_r is similar to var_dump except its output is simpler only the arrays index and value will be shown. If var_dump has the extended attribute of true var_dump($beatles, true); then its value can be returned or stored in a variable.

print_r($Beatles);

Will Output
Array
(
[0] => John
[1] => Paul
[2] => George
[3] => Ringo
)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 3. Arrays | Tags: , , , , ,

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS