|
|
| Php Functions Essential Reference (ISBN: 073570970X) |
 |
List Price: $49.99
Our Price: $34.99
Used Price: $24.35
Release Date:
Manufacturer: New Riders Publishing (Paperback)
Sales Rank: 14,785
Author: Zak Greant, Graeme Merrall, Torben Wilson, Brett Michlitsch
|
More Info
|
|
|
Associative Arrays
|
2003-03-16 14:19:13
|
| |
php
|
|
|
|
|
Category: source:php:general
|
|
Description: Assign, sort and print out all of the values of an associative array.
|
|
Platform: all
|
|
Author: detour
|
|
Viewed: 3494
|
|
Rating: 3/5 (13 votes)
|
|
|
| If you have any questions about
this piece of code or still need help, try posting your question on the forum. |
<?php
/* ass_array.php by detour@metalshell.com
*
* Example on using associative arrays.
*
* http://www.metalshell.com/
*
*/
/** Assigning Values **/
// One at a time.
$ass_array["black"] = "white";
$ass_array["up"] = "down";
// Multiple using array()
$ass_array = array("black" => "white", "up" => "down", "left" => "right", "night" => "day");
/** Displaying the Values **/
echo('<H2>Display values individually</H2>');
echo($ass_array["black"] . ', ' . $ass_array["up"] . '<br><br>');
echo('<H2>Display all values.</H2>');
foreach($ass_array as $key => $value)
echo($key . ' = ' . $value . '<br>');
/* You can also sort the array by either the key or value.
*
* asort() - sort in ascending order
* arsort() = sort in descending order
* ksort() = sort by the key in ascending order
*
*/
asort($ass_array);
// You can also cycle through the array by using a pointer
// Use reset() to set the pointer at the beginning of the array
reset($ass_array);
$num = count($ass_array);
echo('<H2>Display all values using a pointer. Note they are sorted now.</H2>');
for($x = 0; $x < $num; $x++) {
echo(key($ass_array) . ' = ' . current($ass_array) . '<br>');
// Increment the pointer
next($ass_array);
}
?>
|
|
|