PHP Associative Arrays
How to create an associative array ...
<?php
$car = array ("weight"=>"100kg", "year"=>"2004", "price"=>"7000");
?>
Alternative code:
<?php
$car["weight"] = "100kg";
$car["year"] = "2004";
$car["price"] = "7000";
$car["discount rebate"] = "12";
?>
To display the items in an array, do this:
<?php
// display car properties
print($car["price"]."<br>");
// display all car properties
foreach ($car as $property=>$value) {
print($property . " is " . $value . "<br>");
}
?>
How to sort an associative array ...
asort() - Sorts an associative array by value. Returns nothing.
ksort() - Sorts an associative array by key. Returns nothing.
eg.
<?php
$fruittrolley = array ("apple"=>"100", "orange"=>"20", "pear"=>"30");
asort($fruittrolley);
print("After asort: <br>");
foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.<br>");
}
ksort($fruittrolley);
print("After ksort: <br>");
foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.<br>");
}
?>
prints:
After asort:
There are 20 oranges.
There are 30 pears.
There are 100 apples.
After ksort:
There are 100 apples.
There are 20 oranges.
There are 30 pears.
<?php
$car = array ("weight"=>"100kg", "year"=>"2004", "price"=>"7000");
?>
Alternative code:
<?php
$car["weight"] = "100kg";
$car["year"] = "2004";
$car["price"] = "7000";
$car["discount rebate"] = "12";
?>
To display the items in an array, do this:
<?php
// display car properties
print($car["price"]."<br>");
// display all car properties
foreach ($car as $property=>$value) {
print($property . " is " . $value . "<br>");
}
?>
How to sort an associative array ...
asort() - Sorts an associative array by value. Returns nothing.
ksort() - Sorts an associative array by key. Returns nothing.
eg.
<?php
$fruittrolley = array ("apple"=>"100", "orange"=>"20", "pear"=>"30");
asort($fruittrolley);
print("After asort: <br>");
foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.<br>");
}
ksort($fruittrolley);
print("After ksort: <br>");
foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.<br>");
}
?>
prints:
After asort:
There are 20 oranges.
There are 30 pears.
There are 100 apples.
After ksort:
There are 100 apples.
There are 20 oranges.
There are 30 pears.
0 Comments:
Post a Comment
<< Home