例子 11-8. 填充数组
<?php // fill an array with all items from a directory $handle = opendir('.'); while (false !== ($file = readdir($handle))) { $files[] = $file; } closedir($handle); ?> |
数组是有序的。你也可以使用不同的排序函数来改变顺序。更多信息参见数组函数库。您可以用 count() 函数来数出数组中元素的个数。
例子 11-9. 数组排序
<?php sort($files); print_r($files); ?> |
因为数组中的值可以为任意值,也可是另一个数组。这样你可以产生递归或多维数组。
例子 11-10. 递归和多维数组
array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "first", 5 => "second", "third" ) ); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ?> |
您需要注意数组的赋值总是会涉及到值的拷贝。您需要在复制数组时用指向符号&)。
<?php $arr1 = array(2, 3); $arr2 = $arr1; $arr2[] = 4; // $arr2 is changed, // $arr1 is still array(2,3) $arr3 = &$arr1; $arr3[] = 4; // now $arr1 and $arr3 are the same ?> |
- 学习PHP的一些经验
- PHP入门指导:如何学习PHP
- 实例讲解PHP5 新特性
PHP之友评论