You can access an individual element in an array by calling a specific index value.
Gives the result showing :
To run through an entire array, a loop would be used with the each command.
Here's the breakdown :
The total number of elements is calculated.
The FOR loop starts a counter set to zero.
The FOR loop will continue as long as the counter value is less than the number of entries in the array.
The counter is increased by one after each loop is completed.
$line is a temporary array variable. It will hold two values per loop. One value being the KEY or index and the second value being the VALUE of that specific KEY.
The echo command prints out the current values.
And the result is :
<?php
$pantry = array(
1 => "apples",
2 => "oranges",
3 => "bananas"
);
$findit = $pantry[2];
echo "The value of findit is $findit.";
?>
$pantry = array(
1 => "apples",
2 => "oranges",
3 => "bananas"
);
$findit = $pantry[2];
echo "The value of findit is $findit.";
?>
Gives the result showing :
The value of findit is oranges.
To run through an entire array, a loop would be used with the each command.
<?php
$count_total = count($pantry);
for ($counter=0; $counter<$count_total; $counter++){
$line = each ($pantry);
echo "$line[key] $line[value] <br />";
}
?>
$count_total = count($pantry);
for ($counter=0; $counter<$count_total; $counter++){
$line = each ($pantry);
echo "$line[key] $line[value] <br />";
}
?>
Here's the breakdown :
The total number of elements is calculated.
The FOR loop starts a counter set to zero.
The FOR loop will continue as long as the counter value is less than the number of entries in the array.
The counter is increased by one after each loop is completed.
$line is a temporary array variable. It will hold two values per loop. One value being the KEY or index and the second value being the VALUE of that specific KEY.
The echo command prints out the current values.
And the result is :
1 apples
2 oranges
3 bananas
2 oranges
3 bananas

