Practical No. 4: Write A PHP Program For Creating and Manipulating - A) Indexed Array, B) Associative Array, C) Multidimensional Array
Practical No. 4: Write A PHP Program For Creating and Manipulating - A) Indexed Array, B) Associative Array, C) Multidimensional Array
I. Practical Significance
An array is a special variable, which can hold more than one value at a time. For example if
you want to store 100 numbers then instead of defining 100 variables its easy to define an array
of 100 length.
Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
• Two-dimensional Arrays
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays
of arrays). We can store the data from a table in a two-dimensional array, like this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
1
Web Based Application Development Using PHP(22619)
III. Exercise:
1) Indexed Array
Input:
<?php
//Indexed Array
echo "<h2>INDEXED ARRAY</h2>";
$cars = array("Volvo", "BMW", "Toyota");
echo "<b>Printing the array without using for loop</b><br>";
echo "I like " . $cars[0] .", ". $cars[1] ." and ". $cars[2] .".";
Output:
INDEXED ARRAY
2) Associative Array
Input:
<?php
//Associative Array
echo "<br><h2>ASSOCIATIVE ARRAY</h2>";
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "<b>Printing the array without using loop</b><br>";
echo "Peter is " . $age['Peter'] . " years old.";
2
Web Based Application Development Using PHP(22619)
Output:
ASSOCIATIVE ARRAY
3) Multidimensional Array
Input:
<?php
//Multidimensional Array
echo "<br><h2>MULTIDIMENSIONAL ARRAY</h2>";
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
3
Web Based Application Development Using PHP(22619)
Output:
MULTIDIMENSIONAL ARRAY
John Flinch
mob : 9875147536
email : [email protected]
IV. Conclusion
Thus, we have successfully completed the given experiment based on:
Program for creating and manipulating- a) Indexed array, b) Associative array, c) Multidimensional
array