Introduction
Arrays are lists: lists of people, lists of sizes, lists of books. To store a group of related items in a variable, use an array. Like a list on a piece of paper, the elements in array have an order. Usually, each new item comes after the last entry in the array, but just as you can wedge a new entry between a pair of lines already in a paper list, you can do the same with arrays in PHP.
In many languages, there is only one type of array: what is called a numerical array (or just an array). In a numerical array, if you want to find an entry, you need to know its position within the array, known as an index. Positions are identified by numbers: they start at 0 and work upwards one by one.
In some languages, there is also another type of array: an associative array, also known as a hash. In an associative array, indexes aren't integers, but strings.
Creating arrays by using “array()” Function
<?php
$users=array('saman','nimal','madawa','anura');
print_r($users);
?>
|
Creating arrays by using array identifier
<?php
$names[]='saman';
$names[]='nimal';
$names[]='madawa';
$names[100]='anura';
print_r($names);
?>
|
$array = array('cat', 'dog', 'fish', 'rabbit');
|
Think of an array as a variable that can store many separate values. We can access each item in the array.
<?php
$array = array('cat', 'dog', 'fish', 'rabbit');
echo $array[0].'<BR>'; //returns "cat"
echo $array[1].'<BR>'; //returns "dog"
echo $array[2].'<BR>'; //returns "fish"
echo $array[3].'<BR>'; //returns "rabbit"
?>
|
Now each item of the array is accessed using the variable name, followed directly by square brackets containing the number of the item to be accessed. The number listing of the array starts at zero, so the first item is 0, second is 1, third is 2, etc.
Populate Array with array_fill()
<?php
$langs=array_fill(0,4,'php');
print $langs[0].'<BR>';
print $langs[1].'<BR>';
print $langs[2].'<BR>';
print $langs[3].'<BR>';
?>
|
Enumerated Arrays
Arrays that are numerically indexed are called enumerated arrays. The first index that represents the first element is always 0. Consider the following sample code.
|
Associative Arrays
Arrays that are indexed by using strings are called associative arrays. When you use them you specify a string instead of numbers within the square brackets. The => symbol is used to assign values to array using the index.
|
Using the “array()” function
|
Initializing Arrays
A foreach loop
The easiest way to cycle though an array and operate on all or some of the elements inside is to use foreach.
With foreach, PHP iterates over a copy of the array instead of the actual array. In contrast, when using each( ) and for, PHP iterates over the original array. So, if you modify the array inside the loop, you may (or may not) get the behavior you expect.
Example Code
<?php
$Students[]="Kamal";
$Students[]="Saman";
$Students[]="Rani";
foreach($Students as $temp){
echo $temp, "<BR>";
}
?>
|
|
The for loop works only for arrays with consecutive integer keys. Unless you're modifying the size of your array, it's inefficient to recompute the count( ) of $items each time through the loop, so we always use a $size variable to hold the array's size:
<?php
$Students=array("saman1","kama11kl","ravi","nuwan");
for ($item = 0, $size = count($Students); $item < $size; $item++)
{
echo $Students[$item], "<BR>";
}
?>
|
If you prefer to count efficiently with one variable, count backwards:
<?php
$Students=array("saman1","kama11kl","ravi","nuwan");
for ($item = count($Students) - 1; $item >= 0; $item--)
{
echo $Students[$item], "<BR>";
}
?>
|
Exercise
$fruits = array('red' => 'Apples', 'yellow' => 'Bananas');
……………………………..
|
Output
Apples are red.
Bananas are yellow.
<?php
$fruits = array('red' => 'Apples', 'yellow' => 'Bananas');
foreach ($fruits as $key=>$value)
{
echo "$value are $key"."<BR>";
}
?>
Specifying an Array Not Beginning at Element 0
<?php
$fruits = array('red' => 'Apples', 'yellow' => 'Bananas');
foreach ($fruits as $key=>$value)
{
echo "$value are $key"."<BR>";
}
?>
|
Instruct array( ) to use a different index using the => syntax:
<?php
$presidents = array(1 => 'Washington', 'Adams', 'Jefferson', 'Madison');
print_r($presidents);
?>
|
If you're unsure if the data you'll be processing is a scalar or an array, you need to protect against calling foreach with a non-array. One method is to use is_array( ) :
if (is_array($items)) {
// foreach loop code for array
} else {
// code for scalar
}
|
Multidimensional Arrays
<?php
$students =array(
array( "name"=>"saman", "Address"=>"Kandy Rd, Malabe", "TP"=>"+94-812-456789", "Email"=>"Saman@sliit.lk"),
array( "name"=>"Ravindra", "Address"=>"Mt.Lavinia", "TP"=>"+94-812-4125489", "Email"=>"Ravindra@sliit.lk"),
array( "name"=>"Bhagya", "Address"=>"Dehiwala", "TP"=>"+94-812-452368", "Email"=>"Bhagya@sliit.lk")
);
print_r ($students);
echo "<BR><br>";
foreach($students as $temp1){
foreach($temp1 as $key=> $temp2){
echo "$key : $temp2","<br>";
}
echo "<BR>";
}
echo "Count of students".count($students)."<BR>";
?>
|
NOTE: Count The Number of Elements in an Array à count() function
Deleting Elements from an Array
You want to remove one or more elements from an array.
To delete one element, use unset( ):
<?php
$Students=array("saman","kamakl","ravi","nuwan");
print_r($Students);
echo "<BR>";
unset($Students[3]);
print_r($Students);
echo "<BR>";
$Employee =array( "name"=>"saman", "Address"=>"Kandy Rd, Malabe", "TP"=>"+94-812-456789", "Email"=>"Saman@sliit.lk");
print_r($Employee);
echo "<BR>";
unset($Employee['name']);
print_r($Employee);
echo "<BR>";
?>
|
To delete multiple noncontiguous elements, also use unset( ):
<?php
$Students=array("saman","kamakl","ravi","nuwan");
print_r($Students);
echo "<BR>";
unset($Students[3], $Students[2]);
print_r($Students);
echo "<BR>";
$Employee =array( "name"=>"saman", "Address"=>"Kandy Rd, Malabe", "TP"=>"+94-812-456789", "Email"=>"Saman@sliit.lk");
print_r($Employee);
echo "<BR>";
unset($Employee['name'],$Employee['Address']);
print_r($Employee);
echo "<BR>";
?>
|
Checking if a Key Is in an Array
You want to know if an array contains a certain key.
Use isset( ):
<?php
$Employee =array( "name"=>"saman", "Address"=>"Kandy Rd, Malabe", "TP"=>"+94-812-456789", "Email"=>"Saman@sliit.lk");
print_r($Employee);
echo "<BR>";
if (isset($Employee['Address']))
{
echo "Found Address";
}
else
{
echo "Not Found Address";
}
?>
|
Checking if an Element Is in an Array
You want to know if an array contains a certain value.
Use in_array( ):
<?php
$Employee =array( "name"=>"saman", "Address"=>"Kandy Rd, Malabe", "TP"=>"+94-812-456789", "Email"=>"Saman@sliit.lk");
print_r($Employee);
echo "<BR>";
if (in_array('saman',$Employee))
{
echo "Found Saman ";
}
else
{
echo "Not Found Saman";
}
?>
|
Finding the Position of an Element in an Array
You want know if an element is in an array, and, if it is, you want to know where it is located.
Use array_search( ). It returns the key of the found element or false:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;
$key = array_search('red', $array); // $key = 1;
echo $key;
?>
|
Finding the Largest or Smallest Valued Element in an Array
You have an array of elements, and you want to find the largest or smallest valued element.
To find the largest element, use max( ):
$largest = max($array);
|
To find the smallest element, use min( ):
$smallest = min($array);
|
Reversing an Array
You want to reverse the order of the elements in an array.
Use array_reverse( ):
<?php
$input = array("php", 4.0, array("green", "red"));
print_r($input);
$result = array_reverse($input);
print_r($input);
$result_keyed = array_reverse($input, true);
print_r($input);
?>
|
Sorting an Array
You want to sort an array in a specific way.
To sort an array using the traditional definition of sort, use sort( ):
<?php
$fruits = array("lemon", "orange", "banana", "apple");
print_r($fruits)
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>
|
To sort numerically, pass SORT_NUMERIC as the second argument to sort( ).
$scores = array(1, 10, 2, 20);
sort($scores, SORT_NUMERIC);
|
3 comments:
Nice work man... Continue well..
thanks.. ok will do
do something extra
Post a Comment