");
reset($a);
$value = current($a);
print("$value ");
while ($value = next($a))
print("$value ");
print("
");
reset($a);
foreach ($a as $item)
print("$item ");
print("
");
echo "-----1----------------
";
//To see why the for-loop with the index (above) is not a good idea ...
//We add a value to the array $a and do it all again
$a[10] = 555;
print("Size of array: " . count($a));
print("
");
reset($a);
for ($i = 0; $i < count($a); $i++) //Not the best idea in PHP
print("$a[$i] ");
print("
");
reset($a);
$value = current($a);
print("$value ");
while ($value = next($a))
print("$value ");
print("
");
reset($a); foreach ($a as $item)
print("$item ");
print("
");
echo "-----2----------------
";
//Note that we can create some very strange "arrays",
//and note carefully how their values are/can be output.
$b["Sunday"] = 0;
$b['pi'] = 3.14;
$b[7] = 'lucky'; foreach ($b as $item)
print("$item ");
print("
");
echo "$b[Sunday] $b[pi] $b[7]
";
//Note: No single quotes in first or second array element above
echo "-----3----------------
";
//Here are two "associative" arrays in which we create the "keys"
//or "indexes" and the corresponding values at the same time:
$a = [10 => 32, 20 => 35, 15 => 12, 30 => 41, 40 => 47]; foreach ($a as $item)
print("$item ");
print("
");
echo "";
print_r($a);
echo "
";
$a = array("Bob" => 26, "Mary" => 24, "Bill" => 19); foreach ($a as $name => $age)
print("$name's age is $age.
");
echo "";
print_r($a);
echo "
";
echo "-----4----------------
";
//Here's another one of these "associative arrays" from which we
//first access all of the keys and then all of the values:
$a = array("Bob" => 26, "Mary" => 24, "Bill" => 19);
$names = array_keys($a);
$ages = array_values($a); foreach ($names as $name)
print("$name
"); foreach ($ages as $age)
print("$age
");
echo "-----5----------------
";
//Here we sort and then display an array
//which contains both integer and strings:
$a = array("Tom", 15, "Dick", 20, "Harry", 10);
sort($a); foreach ($a as $item)
print("$item ");
print("
");
echo "-----6----------------
";
$a = range(5, 10);
print_r($a);
echo "";
print_r($a);
echo "
";
echo "-----7----------------
";
//Note this more recent way of defining an array with literal values:
$myArray = [1, 2];
$index = 1;
//The following is OK and outputs "value at index 1 is 2"
echo "value at index $index is $myArray[$index]";
//The following is not OK and outputs "Warning: Array to string conversion"
echo "value at index $index is $myArray{$index}";
//So square brackets [ ] are OK in this context but not braces { }.
?>