PHP


// --------------------------------
// one-dimensional array (indexed)
// --------------------------------
$names = array('Joe', 'Sue', 'Jim');

array_push($names, 'Jack'); // add item to end
array_unshift($names, 'Jill'); // add item to beginning
echo $names[0]; // display the first item
sort($names); // sorts the array in ascending order
rsort($names); // sorts the array in descending order
print_r($names); // display the array

// loop through array using for loop
for ($x = 0; $x < count($names); $x++) {
  echo $names[$x] . '<br>';
}

// loop through array using foreach
foreach ($names as $name) {
  echo $name . '<br>';
}

// ------------------------------------
// one-dimensional array (associative)
// ------------------------------------
$ages = array('Bill'=>10, 'Joe'=>20, 'Sue'=>30);
echo $ages['Bill'];

// loop through the array using foreach (display key/value)
foreach ($ages as $key => $value) {
  echo $key . ' - ' . $value . '<br>';
}

// --------------------------------------------------
// multi-dimensional array (both arrays are indexed)
// --------------------------------------------------
$contacts = array(
  array('Bill', 44, 'M'),
  array('Jill', 40, 'F'),
  array('Joe', 59, 'M')
);

// loop through the array (display the age for each contact)
foreach ($contacts as $contact) {
  echo $contact[0] . '<br>';
}

// ------------------------------------------------------------------------
// multi-dimensional array (first array is indexed, second is associative)
// ------------------------------------------------------------------------
$contacts = array(
  array('Name'=>'Bill', 'Age'=>44, 'Gender'=>'M'),
  array('Name'=>'Jill', 'Age'=>40, 'Gender'=>'F'),
  array('Name'=>'Joe', 'Age'=>59, 'Gender'=>'M')
);

// loop through array using foreach (with key/value)
foreach ($contacts as $key => $value) {
  echo $value['Age'] . '<br>';
}

// ------------------------------------------------------
// multi-dimensional array (both arrays are associative)
// ------------------------------------------------------
$contacts = array(
  'Bill'=>array('Age'=>44, 'Gender'=>'M'),
  'Jill'=>array('Age'=>40, 'Gender'=>'F')
);

$contacts['Bill']['Age'] = 45; // update an item in a row
$contacts['Will'] = array('Age'=>59, 'Gender'=>'M'); // add a row

// loop through array using foreach (with key/value)
foreach ($contacts as $key => $value) {
  echo $key . ' - ' . $value['Age'] . '<br>';
}

// -----------------------
// array quiz            
// -----------------------
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g');
$numbers = array(1, 2, 3);
$numbersItem = 0;

for ($x = 0; $x < count($letters); $x++) {
  echo $letters[$x] . $numbers[$numbersItem] . '<br>'; // a1, b2, c3, d1, e2, f3, g1

  $numbersItem++;
  if ($numbersItem >= count($numbers)) {
    $numbersItem = 0;
  }
}