Arrays in PHP
An array variable can store multiple items of data sequential array elements that are number starting at zero . So the first array is value stored in array element number zero Individual array elements value can be referenced using the variables name followed by the index number in square brackets .
for example
$months[0] reference value stored in the first array element
$months[1] reference value stored in second array element
Variable array can be created multiple statement that assign value to successive element
array() function to fill the element
for example
$months[]='January';
$months[]='February';
$months[]='March';
$months = array ('January','February','March');
When creating an array you can optionally specify a key name for each element that can be used to reference that element value
for example
$months['jan']='January';
$months['feb']='February';
$months['mar']='March';
$months=array('jan'=>'January','feb'=>'February','mar'=>'March');
All elements of array can be accessed using a foreach loop to element value in turn and assign it to a variable
for example
foreach ($months as $value )
{
# Use the current $value on each iteration
}
The keys can also be accessed on each iteration of the loop using
for example
foreach ($months as $key =>$value)
{
# Use the current $key and $value on each iteration
}
PHP Program
<?php
$day =array('Monday','Tuesday','Wednesday');
foreach ($day as $value)
{
echo "• $value";
}
?>
<?php
$months=array('jan'=>'January','feb'=>'February','mar'=>'March');
foreach ($months as $key =>$value)
{
echo "<dl>$key <dd>$value";
}
?>
Sorting Arrays
PHP provides two simple function to converts between variable array and string because they are continiously used .
The implode() function converts an array to string and inserts a specified separator between each value
for example
$csv_list = implode(','.$array);
The explode() function converts a string to an array by specifying a seprator around which to brek up the string
for example
$array = explode(','.$csv_list);
PHP provides three useful function to sort array element into ascending alphanumeric order
1 . sort() function - sort by value discarding the original key
2 . asort() function - sorts by value retaining the original key
3 . ksort() function - sort by key
PHP Program
<?php
$cars = array('Dodge'=>'Viper','Chevrolet'=>'Camaro','Ford'=>'Mustang');
echo "Original Element Order ';
foreach($cars as $key=>$value)
{
echo '&bull', $key. ' ' . $value;
}
asort($cars)
echo " Sorted Into Value Order";
foreach($cars as $key=>$value)
{
echo '&bull' , $key . ' ' .$value;
}
ksort($cars)
echo "Sorted Into Key Order";
foreach($cars as $key => $value )
{
echo '•' , $key . ' ' . $value ;
}
?>
Good 🙂
ReplyDelete