Saturday, November 13, 2004

PHP Arrays

How to create an array ...

<?php

$fruitbasket = array ("Apple", "Orange", "Pear", "Mango", "Strawberry");
$fruitbasket[] = "Rambutan"; // add a fruit to the list

?>

Alternatively, you can use the following code:

<?php

$fruitbasket[] = "Apple";
$fruitbasket[] = "Orange";
$fruitbasket[] = "Pear";
$fruitbasket[] = "Mango";
$fruitbasket[] = "Strawberry";
$fruitbasket[] = "Rambutan";

?>

Note: Use count($arrayName) to count the number of items in the array.

To display the items in an array, do this:

<?php

// display fruits in fruitbasket
for($i=0;$i<count($fruitbasket);$i++) {
print($fruitbasket[$i]."<br>");
}

?>

Alternatively, you can use the following code:

<?php

// display fruits in fruitbasket
foreach ($fruitbasket as $item) {
print($item."<br>");
}

?>

0 Comments:

Post a Comment

<< Home