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 to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Multidimensional arrays and array functions

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  2. Node.js Move and Copy file (28420)
  3. MouseEvent - Events for Mouse (2909)
  4. PHPMailer (2311)
  5. Uploading images to server with Ajax (6095)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)