PHP Arrays
จาก Wiki2
เนื้อหา |
Create Arrays by assignment value
$customers[1] = “Sam Smith”;
$customers[2] = “Sue Jones”;
$customers[3] = “Mary Huang”;
$capitals[‘CA’] = “Sacramento”;
$capitals[‘TX’] = “Austin”;
$capitals[‘OR’] = “Salem”;
same as
$capitals = array ( “CA” => “Sacramento”, “TX” => “Austin”, “OR” => “Salem” );
$streets[] = “Elm St.”;
$streets[] = “Oak Dr.”;
$streets[] = “7th Ave.”;
same as
$streets = array ( “Elm St.”,”Oak Dr.”,”7th Ave.”);
$streets = array ( 12 => “Elm St.”,”Oak Dr.”,”7th Ave.”);
same as
$streets[12] = Elm St.
$streets[13] = Oak Dr.
$streets[14] = 7th Ave.
$years = range(2001, 2010);
same as
$years[0]= 2001;
$years[1]= 2002;
. . .
$years[8]= 2009;
$years[9]= 2010;
$reverse_letters = range(“z”, “a”);
same as
$reverse_letters[0]=z
$reverse_letters[1]=y
. . .
$reverse_letters[24]=b
$reverse_letters[25]=a
Viewing Arrays
print_r($customers);
output as
Array
(
[1] => Sam Smith
[2] => Sue Jones
[3] => Mary Huang
)
var_dump($customers);
output as
array(3) {
[1]=>
string(9) “Sam Smith”
[2]=>
string(9) “Sue Jones”
[3]=>
string(10) “Mary Huang”
}
Modifying Arrays
by re-assign
$capitals[‘TX’] = “Big Springs”;
Copy array
$customerCopy = $customers;
Removing value
unset($colors[3]);
unset($colors);
Sorting Arrays
sort($arrayname);
asort($capitals);
rsort($capitals);
Sort Statement What It Does
- sort($arrayname) Sorts by value; assigns new numbers as the keys.
- asort($arrayname) Sorts by value; keeps the same key.
- rsort($arrayname) Sorts by value in reverse order; assigns new num-bers as the keys.
- arsort($arrayname) Sorts by value in reverse order; keeps the same key.
- ksort($arrayname) Sorts by key.
- krsort($arrayname) Sorts by key in reverse order.
- usort($arrayname, Sorts by a function (see Chapter 8 for information functionname) on functions).
- natsort($arrayname) Sorts mixed string/number values in natural order. For example, given an array with values day1, day5, day11, day2, it sorts into the following order: day1,day2, day5, day11. The previous sort functions sort the array into this order: day1, day11, day2, day5.
Using Arrays in Statements
$CAcapital = $capitals[‘CA’];
echo $CAcapital ;
output
Sacramento
echo $capitals[‘TX’];
output
Austin
echo “The capital of Texas is {$capitals[‘TX’]}”;
output
The capital of Texas is Austin
