【编者按】:网学网PHP为您提供PHP之数组学习参考,解决您在PHP之数组学习学习中工作中的难题,参考学习。
今天学习了数组,可以说是PHP的数据应用中较重要的一种方式。PHP的数组函数众多,下面是我学习的小结,借此记之,便于以后鉴之……
一、数组定义:
数组的定义使用 array()方式定义,可以定义空数组:
复制代码 代码如下:
<?php
$number = array(1,3,5,7,9);
//定义空数组
$result = array();
$color =array("red","blue","green");
//自定义键值
$language = (1=>"English",3=>"Chinese",5=>"Franch");
//定义二维数组
$two = array(
"color"=>array("red","blue"), //用逗号结尾
"week"=>array("Monday","Friday") //最后一句没有标点
);
?>
二、创建数组:
创建数组包含的函数有compact()、
1.compact()函数——将一个或多个变量(包含数组)转换为数组:
array compact ( mixed $varname [, mixed $... ] )
复制代码 代码如下:
<?PHP
$number = "1,3,5,7,9";
$string = "I''m PHPer";
$array = array("And","You?");
$newArray = compact("number","string","array");
print_r ($newArray);
?>
compact()函数用于将两个或多个变量转换为数组,当然也包含数组变量。其参数是变量的名称而非带有$全名。
相反的函数是extract()作用顾名思义就是将数组转换为单个的字符串,键值作为其字符串名称,数组值作为字符串的值。
运行结果:
复制代码 代码如下:
Array ( [number] => 1,3,5,7,9 [string] => I''m PHPer [array] => Array ( [0] => And => You? ) )
2.array_combine()——将两个数组重组成一个数组,一个作键值一个做的值:
array array_combine ( array $keys , array $values )
复制代码 代码如下:
<?PHP
$number = array("1","3","5","7","9");
$array = array("I","Am","A","PHP","er");
$newArray = array_combine($number,$array);
print_r ($newArray);
?>
array_combine函数不多说了,谁看了都明白
运行结果:
Array ( => I => Am => A => PHP => er )
3.range()函数——创建指定范围的数组:
不多说了,直接上实例——
复制代码 代码如下:
<?PHP
$array1 = range(0,100,10);//0为起始值,100为结束值,10为步进值(默认步进值为1).
print_r($array1);
echo"<br />";
$array2 = range("A","Z");
print_r($array2);
echo "<br />";
$array3 = range("z","a");
print_r($array3);
?>
range()函数的默认步进值是1!
运行结果:
复制代码 代码如下:
Array ( [0] => 0 => 10 => 20 => 30 => 40 => 50 => 60 => 70 => 80 => 90 [10] => 100 )
Array ( [0] => A => B => C => D => E => F => G => H => I => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z )
Array ( [0] => z => y => x => w => v => u => t => s => r => q [10] => p [11] => o [12] => n [13] => m [14] => l [15] => k [16] => j [17] => i [18] => h [19] => g [20] => f [21] => e [22] => d [23] => c [24] => b [25] => a )
4.array_fill()函数——填充数组函数:
复制代码 代码如下:
<?PHP
$array = range(1,10);
$fillarray = range("a","d");
$arrayFil