SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Arrays (II)

PHP Example #34

Using loops with numeric arrays

This is a more concise way of using foreach() with numeric arrays, as shown in this example. By simply setting a variable name after the as operator, each value will be copied to that variable ($dish in this example). However, with this method there is not possibility to access the keys of the elements. For such, we should use an additional variable that is increased on each iteration. By using a for() loop, we receive the position in the loop control variable; this variable ($i in this example) starts with the value 0 and continues until the value that is the number of elements minus one. See the differences of both methods.

<?php
// Using foreach() with a numeric array
$dinner = array('Sweet Corn and Asparagus',
'Lemon Chicken',
'Braised Bamboo Fungus');
foreach ($dinner as $dish) {
print nl2br("You can eat: $dish\n");
} print nl2br("\n");
// Using for() with a numeric array
$dinner = array('Sweet Corn and Asparagus',
'Lemon Chicken',
'Braised Bamboo Fungus');
for ($i = 0, $num_dishes = count($dinner); $i < $num_dishes; $i++) {
print nl2br("Dish number $i is $dinner[$i]\n");
?>
You can eat: Sweet Corn and Asparagus
You can eat: Lemon Chicken
You can eat: Braised Bamboo Fungus

Dish number 0 is Sweet Corn and Asparagus
Dish number 1 is Lemon Chicken
Dish number 2 is Braised Bamboo Fungus

PHP Example #35

Loops and arrays

Here we retake the example of creating a data table that has alternate row colors, but this time using a for() loop instead of a foreach() one.

<?php
$row_color = array('red', 'green');
$color_index = 0;
$meal = array('breakfast' => 'Walnut Bun',
'lunch' => 'Cashew Nuts and White Mushrooms',
'snack' => 'Dried Mulberries',
'dinner' => 'Eggplant with Chili Sauce');
print '<table summary="Dishes">';
for ($i = 0, $num_dishes = count($dinner); $i < $num_dishes; $i++) {
print '<tr bgcolor="' . $row_color[$i % 2] . '">';
print nl2br("<td>Element $i</td><td>$dinner[$i]</td></tr>\n");
}
print '</table>';
?>
Element 0Sweet Corn and Asparagus
Element 1Lemon Chicken
Element 2Braised Bamboo Fungus

PHP Example #36

Order of elements in an array

Elements in an array are accessed in the same order that they were added to the array. If the order of elements is altered in the statements, a foreach() loop would return the values in that same order, while a for() loop would return them always following the numeric order.

<?php
$letters[0] = 'A';
$letters[1] = 'B';
$letters[3] = 'D';
$letters[2] = 'C';
foreach ($letters as $letter) {
print $letter;
}
print nl2br("\n");
for ($i = 0, $num_letters = count($letters); $i < $num_letters; $i++) {
print $letters[$i];
}
?>
ABDC
ABCD

PHP Example #37

Searching for an element with a certain key

To search for a specific element in an array, we don't need to pass thru the entire array for knowing if that element is there or not. By using the array_key_exists() function, we can easily search for an element with a certain key, thus allowing us to avoid writing a certain amount of code and keeping our code simpler. The function will return true if the element exists in the array.

<?php
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0);
$books = array("The Eater's Guide to Chinese Characters",
'How to Cook and Eat in Chinese');
// This is true
if (array_key_exists('Shrimp Puffs', $meals)) {
Print "Yes, we have Shrimp Puffs.\n";
}
// This is false
if (array_key_exists('Steak Sandwich', $meals)) {
Print "We have a Steak Sandwich.\n"; }
// This is true
if (array_key_exists(1, $books)) {
Print "Element 1 is How to Cook and Eat in Chinese.\n";
}
?>
Yes, we have Shrimp Puffs. Element 1 is How to Cook and Eat in Chinese.

PHP Example #38

Searching for an element with a certain value

In the same fashion than array_key_exists() works the in_array() function, but instead of searching an element by its key, it searches it by its value. Another function called array_search() will allow to retrieve the key of the searched element instead of only if the element is present in the array or not.

Both in_array() and array_search() are case-sensitive.

<?php
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0);
$books = array("The Eater's Guide to Chinese Characters",
'How to Cook and Eat in Chinese');
// This is true
if (in_array(3, $meals)) {
Print "There is a $3 item.\n";
}
// This is true
if (in_array('How to Cook and Eat in Chinese', $books)) {
Print "We have How to Cook and Eat in Chinese.\n";
}
// This is false, for in_array() is case sensitive
if (in_array("the eater's guide to chinese characters", $books)) {
Print "We have The Eater's Guide to Chinese Characters.\n";
}
print nl2br("\n\n");
// With array_search() we can obtain the key of the element instead of only the values true or false
$dish = array_search(6.50, $meals);
if ($dish) {
print "$dish costs \$6.50";
}
?>
There is a $3 item. We have How to Cook and Eat in Chinese.

Eggplant with Chili Sauce costs $6.50