Internet Programming
CSC2233
Department of Computer Science
ARRAYS
[email protected]
H.D Supuni Shashikala
Department of Computer Science,
University of Ruhuna
Outline
Arrays
◦ Introduction
◦ Types
Indexed
Associative
Multidimensional
◦ Functions of arrays
Arrays
⚫ An array is aspecial variable, which can hold
more than one value at atime.
⚫ Arrays store group of related data called
Elements
⚫ An array can hold many values under a single
name, and you can access the values by referring
to an index number.
⚫ Can store heterogeneous data in an array.
Arrays
⚫ PHP arrays can store data of varied types and
automatically organize it for you in a large variety of ways.
⚫ Some of the ways arrays are used in PHPinclude:
◦ Built-in PHP environment variables are in the form of arrays
(e.g. $_POST)
◦ Most database functions transport their info via arrays,
making a compact package of an arbitrary chunk ofdata
◦ It's easy to pass entire sets of HTML form arguments from one page
to another in a single array
◦ Arrays make nice containers for doing manipulations (sorting,
counting, etc.) of any data you develop while executing a single
page'sscript
Array types
⚫ Indexed arrays -Arrays with numeric
index
⚫ Associative arrays -Arrays with named
keys
⚫ Multidimensional arrays -Arrays
containing one or more arrays
Creating arrays
⚫ IndexedArray
There are two ways to create indexed arrays.
1.Direct assignment
⚫ The index can be assigned manually
$cars[0] = "Volvo";
$cars[1] = "BMW";
Creating arrays
IndexedArray
2. The array() construct
⚫ Can be called with no arguments to create an empty array
Ex: $my_array= array(); # creates emptyarray
⚫ Can also pass in acomma-separated list of elements to be stored and the indices will
be automatically created beginning with 0
Ex:$fruit_basket= array('apple','orange','banana','pear');
⚫ Where $fruit_basket[0] == 'apple', $fruit_basket[1] == 'orange',etc
⚫ $products=array("Tires","Oil","Spark Plugs"};
Example
1.
<?php
$colors = array(“Red",“Green",“Blue");
echo “Colors are" . $colors[0] . ", " . $colors [1] .
" and " . $colors[2] . ".";
?>
2.
<?php
$array = array("abc",'a',100,200);
print "first ".$array[0]." second ".$array[1]."
third ".$array[2]." forth ".$array[3];
?>
Using loops to access array
for ( $i=0; $i<3; $i++)
echo $products[$i] ;
Foreach ($products as $current)
echo $current;
Associative arrays
⚫ Associative arrays are arrays that use named keys that you assignto
them.
⚫There are two ways to create an associative array.
1. $prices=array(”Tires"=>100,”oil"=>10,”spark plugs"=>4);
Or
2.
$prices=array ('Tires'=>100);
$prices['oil']=10;
$prices['spark plugs']=4;
or
$prices[‟Tires‟]=100;
$prices['oil']=10;
$prices['spark plugs']=4;
Getting Array Keys and Values as
Arrays with Integer Keys
Ex:
<?php
$table=array("Fry"=>"slurm",
"Leela"=>"PlanEx3011");
$usernames = array_keys($table);
$passwds= array_values($table);
echo $usernames[0]."
pwds".$passwds[0];
?>
Try
• What is the difference in echo, print and print_r ?
Department of Computer Science
[email protected]Ans.
• echo : It is used to display the output of parameters that is passed to it. It
display the outputs one or more strings separated by commas.
• print : Unlike echo, print accepts only one argument at a time. It cannot be
used as a variable function in PHP. The print outputs only the strings. It is slow
compared to that of echo.
• print_r : It outputs the detailed information about the parameter in a format
Department of Computer Science
with its type (of an array or an object), which can be easily understandable by
humans
[email protected]
array_keys
- php Manual documentation
Department of Computer Science
[email protected]<?php
$array = array(0 => 100, "color" => "red");
echo(array_keys($array));
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
ArrayArray ( [0] => 0 [1] => color ) Array ( [0] => 0 [1] => 3
[2] => 4 ) Array ( [0] => color [1] => size )
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
Department of Computer Science
[1] => 3
[2] => 4
[email protected]
)
Array
(
[0] => color
[1] => size
)
Multidimensional arrays
⚫ Multidimensional array is an array containing one or more arrays.
⚫ In a multidimensional array, each element in the main array can also be an
array.
⚫ The dimension of an array indicates the number of indices need to select an
element.
◦ For a two-dimensional array need two indices to select an
element
◦ For a three-dimensional array need three indices to select an
element
Two-dimensional Array
⚫ A two-dimensional array is an array of
arrays.
Name stock sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover In a2D
17 arr ay, 15
$cars = array (array("Volvo",22,18),
array("BMW",15,13),array("Saab",5,2), array("Land
Rover",17,15) );
Name stock sold
Get the output Volvo
BMW
22
15
18
13
Saab 5 2
Land Rover 17 15
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].",
sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].",
sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].",
sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].",
sold: ".$cars[3][2].".<br>";
?>
Output
Department of Computer Science
[email protected]Arrays of Arrays
The elements of an array can be many things other
than a string or integer.
You can even have objects or other arrays.
$products = array(
'paper' =>array(
'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"),
'pens' => array(
'ball'=> "Ball Point", 'hilite' => "Highlighters", 'marker' =>
"Markers"),
'misc' => array(
'tape'=> "StickyTape", 'glue'=> "Adhesives", 'clips' =>
"Paperclips")
);
echo $products["pens"];
echo $products["ball"];
echo $products["pens"]["marker"];
Get the length of an Array
⚫ The count() function is used to
return the
length (the number of elements) of an
array.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop ThroughArrays
<?php
$color=array("Red","Blue","Green");
$arrlength=count($color);
for($x=0;$x<$arrlength;$x++)
{
echo $color[$x];
echo "<br>";
}
?>
Loop Through an Associative Array
<?php
$marks=array("Ruwan"=>35,"Saman"=>3 7,"Ravi"=>43);
foreach($marks as$x=>$x_value)
{
echo "Student Name=" . $x . ", Marks=" .$x_value;
echo "<br>";
}
?>
Output
• StudentName=Ruwan, Marks=35
Student Name=Saman, Marks=37
Student Name=Ravi, Marks=43
Department of Computer Science
[email protected]Loop Through an Multidimensional
Array
<?php
$shop = array( array("rose", 1.25 , 15), array("daisy",
0.75 , 25), array("orchid", 1.15 , 7) );
for ($row = 0; $row < 3; $row++) {
echo "<b>The row number $row</b>";
echo "<ul>";
for ($col = 0; $col < 3; $col++)
{
echo "<li>".$shop[$row][$col]."</li>";
}
echo "</ul>";
}
?>
Mostly used function with arrays
⚫ count()
◦ Get the length of the array
⚫ current()
◦ Returns the current element in an array
⚫ next()
◦ Advance the internal array pointer of an array
⚫ reset()
◦ Sets the internal pointer of an array to its first element
⚫ sort()
◦ Sorts an array
Examples
⚫ $numbers=range(1,10);
⚫ The range function automatically creates the
array for you.
⚫ $odds=range(1,10,2); //
array of the odd
numbers between 1 and 10
Example
<?php
$color=array("Red","Blue","Green");
$mode = current($color); //$mode = 'Red';
echo $mode;
$mode = next($color); //$mode = 'Blue';
echo $mode;
$mode = prev($color); // $mode = 'Red';
echo $mode;
$mode = end($color); // $mode = 'Green';
echo $mode;
$mode = reset($color); // $mode = 'Red';
echo $mode;
Inspecting Arrays
Deleting from Array
⚫ Deleting an element from an array is just like getting rid of
an assigned variable calling the unset() construct
unset($my_array[2]);
unset($my_other_array['yellow‟]); Ex:
<?php
$anArray = array("X", "Y", "Z");
unset($anArray[0]);
//'dumps' the content of $anArray to the page:
var_dump($anArray);
?>
Output
array(2) { [1]=> string(1) "Y" [2]=> string(1) "Z" }
Department of Computer Science
[email protected]Summary
⚫ PHP arrays are a very powerful associative
array as they can be indexed by integers like a
list, or use keys to look values up like a hash
map or dictionary
⚫ PHP arrays maintain order and there are many
options for sorting
Read On :
• https://www.w3schools.com/php/php_ref_array.asp
• extract() function
• Sort functions in PHP (ksort,asort etc.)
Department of Computer Science
[email protected]