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
What attribute makes a radio button or checkbox input selected?
checked="checked" selected="selected" disabled="disabled"
<input type="checkbox" name="a_name" value="value" checked="checked" />
What CSS value scales the background image to the largest size contained within the element?
repeat-x contain linear-gradient
#id {
  background:url("path_to_image.png");
  background-size:contain;
  background-repeat:no-repeat;
}
What operator is used to determine the rest of the division of two numbers?
% * /
var rest8_7 = 8 % 7;
alert(rest8_7);
Indicate the PHP function that rounds a number up to the next highest integer.
floor() ceil() abs()
$nr = ceil(3.5);
echo $nr;        // 4
Multidimensional arrays and array functions

Last accessed pages

  1. The School for Gods (6073)
  2. sPBM - Simple PHP Backup Manager (3390)
  3. querySelector and querySelectorAll (30115)
  4. CSS3 2D transforms (820)
  5. How to get JSON data from JavaScript to PHP (617)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (55)
  2. The Mastery of Love (9)
  3. CSS cursor property - Custom Cursors (9)
  4. CSS3 2D transforms (7)
  5. Read Excel file data in PHP - PhpExcelReader (7)