當前位置:編程學習大全網 - 編程語言 - php數組的例子

php數組的例子

php 中的數組類型有非常多的用途,因此這裏有壹些例子展示數組的完整威力。

<?php// this$a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 );// is completely equivalent with$a['color'] = 'red';$a['taste'] = 'sweet';$a['shape'] = 'round';$a['name'] = 'apple';$a[] = 4; // key will be 0$b[] = 'a';$b[] = 'b';$b[] = 'c';// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),// or simply array('a', 'b', 'c')?>

例子 11-6. 使用 array()

<?php// Array as (property-)map$map = array( 'version' => 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true );// strictly numerical keys$array = array( 7, 8, 0, 156, -10 );// this is the same as array(0 => 7, 1 => 8, ...)$switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 );// empty array$empty = array();?>例子 11-7. 集合

<?php$colors = array('red', 'blue', 'green', 'yellow');foreach ($colors as $color) { echo Do you like $color?/n;}?>上例將輸出: Do you like red?Do you like blue?Do you like green?Do you like yellow? 直接改變數組的值在 php 5 中可以通過引用傳遞來做到。之前的版本需要需要采取別的方法:

例子 11-8. 集合

<?php// php 5foreach ($colors as &$color) { $color = strtoupper($color);}unset($color); /* 確保下面對 $color 的覆蓋不會影響到前壹個數組單元 */// 之前版本的方法foreach ($colors as $key => $color) { $colors[$key] = strtoupper($color);}print_r($colors);?>上例將輸出: Array( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW) 本例產生壹個基於壹的數組。

例子 11-9. 基於壹的數組

<?php$firstquarter = array(1 => 'January', 'February', 'March');print_r($firstquarter);?>上例將輸出: Array( [1] => 'January' [2] => 'February' [3] => 'March')*/?> 例子 11-10. 填充數組

<?php// fill an array with all items from a directory$handle = opendir('.');while (false !== ($file = readdir($handle))) { $files[] = $file;}closedir($handle);?>數組是有序的。也可以使用不同的排序函數來改變順序。更多信息參見數組函數。可以用 count() 函數來數出數組中元素的個數。

例子 11-11. 數組排序

<?phpsort($files);print_r($files);?>因為數組中的值可以為任意值,也可是另壹個數組。這樣可以產生遞歸或多維數組。

例子 11-12. 遞歸和多維數組

<?php$fruits = array ( fruits => 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 aboveecho $fruits[holes][5]; // prints secondecho $fruits[fruits][a]; // prints orangeunset($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?>

  • 上一篇:電腦任務管理器裏面的進程哪些可以關掉不用?
  • 下一篇:好吧 就問壹下諾記n9和魅族mx哪個好
  • copyright 2024編程學習大全網