Unit - 4 Arrays: Dr. P S V S Sridhar Assistant Professor (SS) Centre For Information Technology
Unit - 4 Arrays: Dr. P S V S Sridhar Assistant Professor (SS) Centre For Information Technology
ARRAYS
Dr. P S V S Sridhar
Assistant Professor (SS)
Centre for Information Technology
-An array can store one or more values in a single variable name.
$arrayname[]=value
Jul
Jan2012
2013 © 2012 UPES
Array in PHP
1) Numeric Array
2) Associative Array
3) Multidimensional Array
Jul
Jan2012
2013 © 2012 UPES
Numeric Array
- A numeric array stores each element with a numeric ID key.
- 2 ways to write a numeric array.
1. Automatically
Example: $names = array("Peter","Quagmire","Joe");
2. Manually
Example1: $names[0] = "Peter"; $names[1] = "Quagmire";
$names[2] = "Joe";
Example 2: $name[] =”Peter”; $name[] =“Quagmire”; $name[] = “joe”;
In the above case we are adding sequential elements that should have
numerical counting upward from zero.
Jul
Jan2012
2013 © 2012 UPES
Associative Arrays
-An associative array, each ID key is associated with a value.
-When storing data about specific named values, a numerical
array is not always the best way to do it.
-With associative arrays we can use the values as keys and
assign values to them.
Example: Using an array to assign an age to a person.
$ages = array(”Brent"=>42, ”Andrew"=>25, "Joshua”=>16);
$ages[‟Brent'] = 42;
$ages[‟Andrew'] = 25;
$ages['Joshua'] = 16;
Eamample:
$f = array(0=>”apple”, 1=>”orange”, 2=>”banana”, 3=>”pear”);
In the above example index values are 0,1,2,3
Jul
Jan2012
2013 © 2012 UPES
Array creation:
following creates an array with numeric index
$icecream_menu=array(275,160,290,250);
$icecream_menu=array(0=>275,1=>160,2=>290,3=>250);
Arrays can be created with other scalar values as well as mix of them
$icecream_menu1[-1]=275;
$icecream_menu1[„item 2‟]=160;
$icecream_menu1[3.4]=290;
$icecream_menu1[false]=250;
An array with a mix of all values can also be created
$icecream_menu=array(-1=>275,'item 2'=>160,3.4=>290,false=>250);
Jul
Jan2012
2013 © 2012 UPES
Creating an Empty Array
$marks=array();
Jul
Jan2012
2013 © 2012 UPES
Finding the Size of an Array
The count() function is used to find the number of elements in the array
Jul
Jan2012
2013 © 2012 UPES
Printing an Array in a readable way
The print_r() ,when passed an array, prints its contents in a readable
way.
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco
Dip'=>290,'Oreo Cherry'=>250);
print_r($icecream_menu);
Jul
Jan2012
2013 © 2012 UPES
Iterating Array Elements
The easiest way to iterate through each element of an array is with
foreach(). The foreach()construct executes the block of code once for
each element in an array.
Syntax
foreach($array as [$key =>] [&] $value)
Jul
Jan2012
2013 © 2012 UPES
Modifying Array while iteration
Arrays can be modified during iteration in 2 ways.
Direct Array Modification
Indirect Array Modification
Jul
Jan2012
2013 © 2012 UPES
Direct Array Modification
Say for example we need to increase the price of the all icecreams by 50 .The following code helps us to update the
price and display the revised price along with the old ones
<html>
<body>
<h3 align="center"><i>Chillers...</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
<?php
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);
foreach($icecream_menu as $key=>$value)
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
?>
</table>
<h3 align="center"><i>Chillers Revised Price.....</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
Jul
Jan2012
2013 © 2012 UPES
Contd…
<?php
foreach($icecream_menu as $key=>&$value)
{
//increase the price of all icecreams by 50
$icecream_menu[$key]=$value+50;
$value=$icecream_menu[$key];
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}
?>
</table>
</body>
</html>
Jul
Jan2012
2013 © 2012 UPES
Indirect Array Modification
foreach($array as [$key =>] [&] $value) {
}
where “&‟ can be used with $value.Any change in $value,indirectly modifies
the value of the array for the current key during the iteration.
foreach($icecream_menu as $key=>&$value)
$value=$value+50;
print "<td>".$key."</td><td>".$value."</td>";
print "</tr>";
}
Jul
Jan2012
2013 © 2012 UPES
Iterating Array with Numeric index
Arrays with numeric index can be accessed using
foreach() and for()
Ex1:
$hobbies=array("Reading Books","Playing Golf","Watching
Tennis","Dancing");
foreach($hobbies as $hobby)
{
print "<br> $hobby ";
}
Ex 2:
for($i=0,$arraysize=count($hobbies);$i<$arraysize;$i++)
Output:
[sam] => array([1] =>79
[2] =>74
)
[ellen] => array([1] => 69
[2] => 84
)
Jul
Jan2012
2013 © 2012 UPES
Handling Multidimensional arrays
Ex:
$scores[“sam”][] = 79;
$scores[“sam”][] = 74;
$scores[“ellen”][] = 69;
$scores[“ellen”][] = 84;
Here index start from 0.
Ex:
$scores = array(“sam” => array(79,74), “ellen” => array(69,84));
Jul
Jan2012
2013 © 2012 UPES
Multi dimensional arrays in loops
$scores[0][] = 79;
$scores[0][] = 74;
$scores[1][] = 69;
$scores[1][] = 84;
for($outer = 0; $outer < count($scores); $outer++)
for($inner = 0; $inner < count($scores[$outer]); $inner++)
{
echo $scores[$outer][$inner];
}
Jul
Jan2012
2013 © 2012 UPES
Splitting and Merging Arrays
array_slice function will split array
Ex1:
$ice_cream[“good”] = “orange”;
$ice_cream[“better”] = “vanilla”;
$ice_cream[“best”] = “rum raisin”;
$ice_cream[“bestest”] = “lime”;
$subarray = array_slice($ice_cream, 1,2);
The index value of better and best will be stored in $subarray as vanilla rum raisin
Ex2:
<?php
$input = array("a", "b", "c", "d", "e");
?>
Output:
fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange
Jul
Jan2012
2013 © 2012 UPES
Sorting of Arrays
Ksort - Sorts the array by key along with value
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
Output:
a = orange b = banana c = apple d = lemon
Jul
Jan2012
2013 © 2012 UPES
Sorting of Arrays
asort - Sorts array by value, keeping key association
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" =>
"apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
Output:
c = apple b = banana d = lemon a = orange
Jul
Jan2012
2013 © 2012 UPES
Array functions
count($ar) - How many elements in an array
array_sum($ar) – sum of array values.
sizeof($ar) – Identical to count()
is_array($ar) - Returns TRUE if a variable is an array
sort($ar) - Sorts the array values (loses key)
ksort($ar) - Sorts the array by key along with value
asort($ar) - Sorts array by value, keeping key association
shuffle($ar) - Shuffles the array into random order
$a = array() – Creates an array $a with no elements
$a = range(1,5) – Create an array between 1 and 5. i.e., $a =
array(1,2,3,4,5)
in_array() – Takes two arguments: an element and an array. Returns
true if the element contained as a value in the array.
rsort(), arsort(), krsort() - Works similar to sort(), asort() and ksort()
except that they sort the array in descending order
Jul
Jan2012
2013 © 2012 UPES
Array functions
list():
Assign array values to variable.
Ex: $f = array(„apple‟,‟orange‟,‟banana‟);
list($r,$o) = $f;
The string apple is assigned to $r and orange is assigned to $o and no assignment of
string banana.
reset():
Gives us a way to “rewind” that pointer to the beginning – it sets the pointer to the first
key/value pair and then returned to stored value.
next():
which moves the current pointer ahead by one,
prev():
Which moves the pointer back by one.
current():
Returns the current element in an array
end()
Which moves
Jul to
Jan2012
2013
end of the array © 2012 UPES
Next, current, Prev
<?php
?>
Jul
Jan2012
2013 © 2012 UPES
Array functions
Deleting from arrays: Just call unset()
$a[0] = “wanted”;
$a[1]=“unwanted”;
$a[2]=“wanted again”;
unset($a[1]);
Deletes 1 key value. Now the above array contains two key values (0,2)
Jul
Jan2012
2013 © 2012 UPES
Extracting Data from Arrays
Extract function to extract data from arrays and store it in variable.
$ice_cream[“good”] = “orange”;
$ice_cream[“better”] = “vanilla”;
$ice_cream[“best”] = “rum raisin”;
extract($ice_cream);
echo “\$good = $good <br>”;
echo “\$better = $better <br>”;
echo “\$best = $best <br>”;
Output:
$good = orange
$better = vanilla
$best = rum raisin
Jul
Jan2012
2013 © 2012 UPES
Arrays and Strings
explode(): The function explode converts string into array format .
We can use explode() to split a string into an array of strings
$inp = "This is a sentence with seven words";
$temp = explode(‘ ', $inp);
print_r($temp);
Output:
Array( [0] => This [1] => is [2] => a [3] => sentence [4] => with
[5] => seven [6] => words)
implode(): To combine array of elements in to a string
$p = array("Hello", "World,", "I", "am", "Here!");
$g = implode(" ", $p);
Output: Hello World I am Here
Jul
Jan2012
2013 © 2012 UPES
Arrays and strings
str_replace():
$rawstring = "Welcome Birmingham parent! <br />
Your offspring is a pleasure to have! We believe pronoun is learning a lot.<br />The faculty
simple adores pronoun2 and you can often hear them say \"Attah sex!\"<br />";
$placeholders = array('offspring', 'pronoun', 'pronoun2', 'sex');
$malevals = array('son', 'he', 'him', 'boy');
$femalevals = array('daughter', 'she', 'her', 'girl');
$malestr = str_replace($placeholders, $malevals, $rawstring);
$femalestr = str_replace($placeholders, $femalevals, $rawstring);
echo "Son: ". $malestr . "<br />";
echo "Daughter: ". $femalestr;
Jul
Jan2012
2013 © 2012 UPES
Jul
Jan2012
2013 © 2012 UPES