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 defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Multidimensional arrays and array functions

Last accessed pages

  1. Working with MySQL Database (3058)
  2. Using v-model in form input fields (847)
  3. Vue JS - Short presentation (385)
  4. Include and Require (1425)
  5. PHP SimpleXML (2360)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (250)
  2. Read Excel file data in PHP - PhpExcelReader (90)
  3. PHP Unzipper - Extract Zip, Rar Archives (75)
  4. The Four Agreements (73)
  5. The Mastery of Love (66)
Chat
Chat or leave a message for the other users
Full screenInchide