Php-mysql Course

Multidimensional arrays

A multidimensional array is an array that has a value of an element as another array. Each element in the main array can also be an array. And each element in the sub-array can be an array.

  - Syntax:
$arr[index1] = array(key1=>value1, key2=>value2);
$arr[index2] = array(key1=>value1, key2=>value2);
 ...
$arr is the name of the main array.
  - Example:
<?php
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');
?>
As you can notice, you can combine numeric and associative arrays. The key of the 'nature' is 0. The value of the other elements is another array (called sub-array).
This is called a two-dimensional array.

Accessing a specific sub-array's element

To access the value of a specific element of an sub-array, use the fallowing syntax:
$main_array[key_main_array][key_sub_array]
This syntax is for a two-dimensional array. You can also use it to modify the value of a sub-array element or add more items in the sub-array.
  - Example:
<?php
// define a two-dimensional array
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');

// gets the value of first element of the 'fruits' sub-array
$fruit1 = $life['fruits'][0];
echo 'I like '. $fruit1;             // I like apples

// modifies the value of first element of the 'fruits' sub-array
$life['fruits'][0] = 'grapes';
echo '<br /> I like '. $life['fruits'][0];             // I like grapes

// adds one more item in the 'vegetables' sub-array
$life['vegetables'][] = 'onions';
echo '<br /> Now, the "vegetables" sub-array has '. count($life['vegetables']). ' elements';
?>
This code will output:
I like apples
I like grapes
Now, the "vegetables" sub-array has 4 elements

Traversing multidimensional Arrays

To walk through, or traverse, a multidimensional array, you have to use nested foreach() instructions.
To learn how to traverse a multidimensional array, study the following example:
<?php
// define a two-dimensional array
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');

foreach ($life as $k => $v) {
  // if $v is an Array, appllies another foreach() loop to it, to get its elements
  if(is_array($v)) {
    foreach ($v as $key => $val) {
      echo '<br />'. $k. ' - '. $key. ' : '. $val;
    }
  }
  else echo '<br />'. $k. ' - '. $v;
}
?>
The first foreach() loop gets the key and the value of each element of the main array ($life). Inside this loop we check if the value of the current element is an array (with "is_array()"). If this function returns True, we create a second foreach() to traverse that sub-array, getting its keys and values.
This code will output:
0 - nature
fruits - 0 : apples
fruits - 1 : banana
fruits - 2 : apricots
vegetables - 0 : tomatoes
vegetables - 1 : cabbage
vegetables - 2 : pumpkin

If you want to get only the values of the array, you can use:   foreach ($array as $value).   It will ignore the key portion.
If you want to get only the keys of the array, you can use:   foreach(array_keys($a) as $key)

Array Functions

There are very many built-in PHP functions for working with arrays. Here, I pick out some of the most used of these functions, you can get the full list at the official web site: Array functions.

Output the array structure

If you want to see the structure of an array, you can use: print_r() or var_export() function.
  - Example:
<?php
$life[] = 'nature';
$life['fruits'] = array('apples', 'banana', 'apricots');
$life['vegetables'] = array('tomatoes', 'cabbage', 'pumpkin');

print_r($life);
echo '<hr />';
var_export($life);
?>
This code will output:
Array ( [0] => nature [fruits] => Array ( [0] => apples [1] => banana [2] => apricots ) [vegetables] => Array ( [0] => tomatoes [1] => cabbage [2] => pumpkin ) )
array ( 0 => 'nature', 'fruits' => array ( 0 => 'apples', 1 => 'banana', 2 => 'apricots', ), 'vegetables' => array ( 0 => 'tomatoes', 1 => 'cabbage', 2 => 'pumpkin', ), )

Using current(), next(), prev(), and end()

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. Another way to access the items' value of an array is to get them one by one with the fallowing PHP functions: - Example:
<?php
$code = array(10=>"Perl", 20=>"PHP", 21=>"Python", 30=>"JavaScript");
$curent = current($code);
  echo "
the current() function returned: $curent"; $nxt = next($code); echo "
the next() function returned: $nxt"; $nxt = next($code); echo "
the next() function returned: $nxt"; $prv = prev($code); echo "
the prev() function returned: $prv"; $last = end($code); echo "
the end() function returned: $last"; ?>
Output:
the current() function returned: Perl
the next() function returned: PHP
the next() function returned: Python
the prev() function returned: PHP
the end() function returned: JavaScript

Sorting Arrays

Array's elements can be organized and reorganized in many ways, through the sorting functions. With these functions you can change the order of the elements from lowest to highes and vice versa, based on their values and keys.
Here is this sorting functions, each one with an example (I use the var_export() function to show the array structure after the sorting process):

Other PHP functions for array

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used in <table> to create table header cell?
<thead> <th> <td>
<table><tr>
  <th>Title 1</th>
  <th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin
.some_class {
  line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()
document.getElementById("id_button").onclick = function(){
  window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()
$ar_dir = scandir("dir_name");
var_export($ar_dir);
Multidimensional arrays and array functions

Last accessed pages

  1. Zodiac Signs PHP code (7232)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142534)
  3. The Essene Gospel of Peace (2504)
  4. CSS3 Flexbox Container (1086)
  5. Movie Clip Symbols (2327)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (537)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)