array()
方法array()函数是PHP中的预定义函数,用于创建元素数组,数组数组等。
通过使用array()函数,我们可以创建两种类型的数组,
索引数组
关联数组(具有键和值的数组)
而且,多维数组
创建索引数组的语法:
array(element1, element2, element2, ...);
用键创建数组的语法:
array(key1=>value1, key2=>value2, key3=>value3, ...);
PHP代码:
在这里,我们将创建一个索引数组,并使用一个一个元素(使用索引)打印该数组,并打印整个数组。
<?php //数字数组 $arr_num = array(10, 20, 30, 40, 50); //使用字符串数组 $arr_string = array("Laptop", "Mobile", "Tablet"); //具有混合类型的数组 $arr_mixed = array("Hello", 10, "friends", 20); //打印数组元素 print ("Array elements: $arr_num[0], $arr_num[1], $arr_num[2], $arr_num[3], $arr_num[4]\n"); print ("Array elements: $arr_string[0], $arr_string[1], $arr_string[2]\n"); print ("Array elements: $arr_mixed[0], $arr_mixed[1], $arr_mixed[2], $arr_mixed[3]\n"); //打印完整的数组 print ("arr_num is...\n"); print_r ($arr_num); print ("arr_string is...\n"); print_r ($arr_string); print ("arr_mixed is...\n"); print_r ($arr_mixed); ?>
输出结果
Array elements: 10, 20, 30, 40, 50 Array elements: Laptop, Mobile, Tablet Array elements: Hello, 10, friends, 20 arr_num is... Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 ) arr_string is... Array ( [0] => Laptop [1] => Mobile [2] => Tablet ) arr_mixed is... Array ( [0] => Hello [1] => 10 [2] => friends [3] => 20 )
PHP代码:
在这里,我们将创建关联(具有键和值的数组)并使用键来打印元素,并打印整个数组。
<?php //creating student array with keys & values $std = array('id' => "101", 'name' => "Amit", 'course' => "B.Tech"); //打印元素 print ("std elements...\n"); print ("Id = " . $std['id'] . " Name = " . $std['name'] . " Course = " . $std['course']); //打印完整的数组 print ("std...\n"); print_r($std); ?>
输出结果
std elements... Id = 101 Name = Amit Course = B.Techstd... Array ( [id] => 101 [name] => Amit [course] => B.Tech )