PHP Multidimensional and Associative Arrays Example

PHP Multidimensional and Associative Arrays Example 


An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID which is called array index.

  • Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
  • Associative array - An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array - An array containing one or more arrays and values are accessed using multiple indices
Array


---------------------CODE------------------

<?php

// SIMPLE ARRAY OF CUSTOMERS NAMES
$customers=array('Mark James','Paul Dodds','Sam Wilson','George Bush');

// LOOP THROUGH THE NAME TO SHOW CONTENTS OF ARRAY
for($x=0; $x<count($customers); $x++)
 echo($customers[$x]."<br>");


// Associative Array 
// The array associates a number to a element of the array, in this case we associate quantity of a product

$products=array('Shoes'=>300,'nails'=>200,'corn flakes'=>500);

//Displays how many pairs of shoes are left in stock
echo('<br><br>Pairs of shoes left in stock : '.$products['Shoes']); 

//Multidimensional array

$instock=array('cars'=>array('Ford','Vauxhall','VW'),
               'motorcycles'=>array('Suzuki','Yamaha','Honda'.'<br>'));

echo("<br><br>");            

// Display all cars in stock via looping through multidimensional array
echo('Cars in Stock : ');
for($x=0; $x<count($instock); $x++) 
    echo($instock['cars'][$x].', ');

// Display all cars in stock via looping through multidimensional array
echo("<br><br>");      
 
echo('Motorcycles in Stock : ');
for($x=0; $x<count($instock); $x++) 
    echo($instock['motorcycles'][$x].', ');

?>

-----------OUTPUT----

Mark James
Paul Dodds
Sam Wilson
George Bush


Pairs of shoes left in stock : 300

Cars in Stock : Ford, Vauxhall,

Motorcycles in Stock : Suzuki, Yamaha,



No comments:

Post a Comment