An array holds a list of data items sequentially. Typically, these items are selected and accessed via a numeric index.
The program below creates an empty array called: $saDaysOfTheWeek. This array is printed out three times than filled and printed again using the same three methods. After that, we print the size of the array. Then the array is printed three more times in different ways to demonstrate common array usage.
<?php // Arrays (basic operations) // Create an empty array and print it in three ways $saDaysOfTheWeek = array(); echo "<b>Three Outputs of an Empty Array:</b><br />"; echo "<b>print_r():</b> "; print_r($saDaysOfTheWeek); echo "<br /><b>var_dump():</b> "; var_dump($saDaysOfTheWeek); echo "<br /><b>var_export():</b> "; var_export($saDaysOfTheWeek); echo "<br /><br />"; // Push entries into the array array_push($saDaysOfTheWeek, "Monday"); array_push($saDaysOfTheWeek, "Tuesday"); array_push($saDaysOfTheWeek, "Wednesday"); array_push($saDaysOfTheWeek, "Thursday"); array_push($saDaysOfTheWeek, "Friday"); array_push($saDaysOfTheWeek, "Saturday"); array_push($saDaysOfTheWeek, "Sunday"); // Print the filled array in the same three ways echo "<b>Three Outputs of a Filled Array:</b><br />"; echo "<b>print_r():</b> "; print_r($saDaysOfTheWeek); echo "<br /><b>var_dump():</b> "; var_dump($saDaysOfTheWeek); echo "<br /><b>var_export():</b> "; var_export($saDaysOfTheWeek); echo "<br /><br />"; // Get the size of the array echo "The array has ".count($saDaysOfTheWeek)." entries.<br /><br />"; // Use a foreach loop to print each entry echo "<b>Foreach loop over Days:</b><br />"; foreach ($saDaysOfTheWeek as $sDay) { echo "{$sDay}<br />"; } echo "<br />"; // Use a foreach loop to print each key with its value echo "<b>Foreach loop with Key=>Value Pairs:</b><br />"; foreach ($saDaysOfTheWeek as $key => $value) { echo "{$key} => {$value} "; } echo "<br /><br />"; // Use a for loop to print each entry via the index echo "<b>For loop with Index Access:</b><br />"; $iSize = count($saDaysOfTheWeek); for ($i = 0; $i < $iSize; ++$i) { echo "{$saDaysOfTheWeek[$i]}<br />"; } ?>
© 20072024 XoaX.net LLC. All rights reserved.