Hot File

Multidimensional Arrays in PHP

View: 432    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Forum PHPBB, VBB   Fields: Other

9 point/3 review File has been tested

Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices. But if you need to keep more than one item of each type you need to use something different

Introduction

Two-dimensional Arrays :

Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices. But if you need to keep more than one item of each type you need to use something different - one of the ways to do it is using multidimensional arrays. The table below might represent our two-dimensional array. Each row represents a type of flower and each column – a certain attribute.

Title Price Number
rose 1.25 15
daisy 0.75 25
orchid 1.15 7

To store data in form of array represented by preceding example using PHP, let’s prepare the following code:

<?php 
$shop = array( array("rose", 1.25 , 15),
               array("daisy", 0.75 , 25),
               array("orchid", 1.15 , 7) 
             ); 
?>

This example shows that now $shop array, in fact, contains three arrays.  As you remember, to access data in one-dimensional array you have to point to array name and index. The same is true in regards to a two-dimensional array, with one exception: each element has two indexes – row and column.

To display elements of this array we could have organize manual access to each element or make it by putting For loop inside another For loop :

<?php 
echo "<h1>Manual access to each element</h1>";

echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";

echo "<h1>Using loops to display array elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    for ($col = 0; $col < 3; $col++)
    {
        echo "<li>".$shop[$row][$col]."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>

Perhaps, instead of the column numbers you prefer to create their names. For this purpose, you can use associative arrays.  The following code will store the same set of flowers using column names:

<?php 
$shop = array( array( Title => "rose", 
                      Price => 1.25,
                      Number => 15 
                    ),
               array( Title => "daisy", 
                      Price => 0.75,
                      Number => 25,
                    ),
               array( Title => "orchid", 
                      Price => 1.15,
                      Number => 7 
                    )
             );
?>

It is easier to work with this array, in case you need to get a single value out of it. Necessary data can be easily found, if you turn to a proper cell using meaningful row and column names that bear logical content.  However, we are loosing the possibility to use simple for loop to view all columns consecutively.

You can view outer numerically indexed $shop array using the for loop. Each row of the $shop array is an associative array.  Hence, inside the for loop you need for each loop.  Also you can get each element from associative array manualy:

<?php 
echo "<h1>Manual access to each element from associative array</h1>";

for ($row = 0; $row < 3; $row++)
{
    echo $shop[$row]["Title"]." costs ".$shop[$row]["Price"]." and you get ".$shop[$row]["Number"];
    echo "<br />";
}

echo "<h1>Using foreach loop to display elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    foreach($shop[$row] as $key => $value)
    {
        echo "<li>".$value."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>

Three-dimensional Arrays :

You don’t have to be limited by two dimensions: the same way as array elements can contain other arrays, these arrays, in their turn, can contain new arrays. 

Three-dimensional array is characterized by height, width, and depth. If you feel comfortable to imagine two-dimensional array as a table, then imagine a pile of such tables.  Each element can be referenced by its layer, row, and column.

If we classify flowers in our shop into categories, then we can keep data on them using three-dimensional array. We can see from the code below, that three-dimensional array is an array containing array of arrays:

<?php 
$shop = array(array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   ),
              array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   ),
              array(array("rose", 1.25, 15),
                    array("daisy", 0.75, 25),
                    array("orchid", 1.15, 7) 
                   )
             );
?>

As this array has only numeric indexes, we can use nested for loops to display it:

<?php
echo "<ul>";
for ( $layer = 0; $layer < 3; $layer++ )
{
    echo "<li>The layer number $layer";
    echo "<ul>";
   
    for ( $row = 0; $row < 3; $row++ ) 
    {
       echo "<li>The row number $row";
       echo "<ul>";
     
        for ( $col = 0; $col < 3; $col++ )
        {
            echo "<li>".$shop[$layer][$row][$col]."</li>";
        } 
        echo "</ul>";
        echo "</li>";
    }
    echo "</ul>";
    echo "</li>";
}   
echo "</ul>";
?>

This way of creating multidimensional arrays allows to create four- and five-dimensional arrays. Syntax rules do not limit the number of dimensions, but the majority of practical tasks logically correspond to the constructions of three or less dimensions.

Multidimensional Arrays in PHP

Multidimensional Arrays in PHP Posted on 15-12-2015  Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices. But if you need to keep more than one item of each type you need to use something different 3/10 432

Comment:

To comment you must be logged in members.

Files with category

  • Input Validation Using Filter Functions with php

    View: 374    Download: 0   Comment: 0   Author: none  

    Input Validation Using Filter Functions with php

    Category: Forum PHPBB, VBB
    Fields: Other

    2.25/2 review
    Filter functions in PHP might not be sexy, but they can improve the stability, security, and even maintainability of your code if you learn how to use them correctly.

  • The Open/Closed Principle in PHP

    View: 255    Download: 0   Comment: 0   Author: none  

    The Open/Closed Principle in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/2 review
    As usual, a good way to grasp what’s actually behind the curtain of the principle and how to take advantage of its benefits is by example. In this article I’ll be setting up a few approachable ones in an attempt to unveil the principle’s driving...

  • Dependency Injection with Pimple in PHP

    View: 291    Download: 0   Comment: 0   Author: none  

    Dependency Injection with Pimple in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    1.6666666666667/3 review
    In application development, we try to create independent modules so that we can reuse code in future projects. But, it’s difficult to create completely independent modules which provide useful functionality; their dependencies can cause maintenance...

  • Working with Directories in PHP

    View: 417    Download: 0   Comment: 0   Author: none  

    Working with Directories in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.25/2 review
    Let's start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a...

  • Guide to Email (Text / HTML / Attachments) in PHP

    View: 397    Download: 0   Comment: 0   Author: none  

    Guide to Email (Text / HTML / Attachments) in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/2 review
    At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters.

  • Dynamic Image Generation in PHP

    View: 343    Download: 0   Comment: 0   Author: none  

    Dynamic Image Generation in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/1 review
    At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

  • Form Processing with PHP

    View: 618    Download: 0   Comment: 0   Author: none  

    Form Processing with PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.6666666666667/3 review
    Before you can process the information, you need to create an HTML form that will send information to your PHP script. There are two methods for sending data: POST and GET. These two types of sending information are defined in your HTML form...

  • Function in PHP

    View: 514    Download: 0   Comment: 0   Author: none  

    Function in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.5/2 review
    A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code contained within functions is ignored...

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd