Home php教程 php手册 PHP学习笔记之数组篇

PHP学习笔记之数组篇

Jun 06, 2016 pm 08:37 PM
array

其实PHP中的数组和JavaScript中的数组很相似,就是一系列键值对的集合。

一、如何定义数组:在PHP中创建数组主要有两种方式,下面就让我们来看看如何创建一个数组

(1)直接给每个元素赋值的方法创建数组。

格式为:$arrayname[key]=value;

其中arrayname为数组的名字,key为数组的元素的键,value为元素的值。键可以是0,1,2,3这一类数字,也可以是字符串。如下所示:
代码如下:
1 2 //用1,2,3的数值作为数组的键
3 echo '

数组$array1的键值为:

';
4 $array1[1]='a';
5 $array1[2]='b';
6 $array1[3]='c';
7 print_r($array1);
8
9 //如果省略键的方式,则数组默认的键为从0开始递增的数值
10 echo '

数组$array2的键值为:

';
11 $array2[]='a';
12 $array2[]='b';
13 $array2[]='c';
14 print_r($array2);
15
16 //以字符串作为数组的键
17 echo '

数组$array3的键值为:

';
18 $array3['one']='a';
19 $array3['two']='b';
20 $array3['three']='c';
21 print_r($array3);
22 ?>

以上代码输出地结果为:

数组$array1的键值为:

Array ( [1] => a [2] => b [3] => c )
数组$array2的键值为:

Array ( [0] => a [1] => b [2] => c )
数组$array3的键值为:

Array ( [one] => a [two] => b [three] => c )

(2)用array函数直接定义一个数组。

格式为:$arrayname=array(key1=>value1,key2=>value2);

其中arrayname为数组名称,key1、key2为数组的键,value1、value2分别对应key1和key2的值。

举一个例子,如以下代码:
代码如下:
1 2 //以数值作为键
3 $array6=array(1=>'a',2=>'b',3=>'c');
4 echo '

数组$array6的键和值为:

';
5 print_r($array6);
6 //以字符串作为键
7 $array7=array('one'=>'a','two'=>'b','three'=>'c');
8 echo '

数组$array7的键和值为:

';
9 print_r($array7);
10 //省略键的写法
11 $array8=array('a','b','c');
12 echo '

数组$array8的键和值为:

';
13 print_r($array8);
14 ?>

其结果为:

数组$array6的键和值为:

Array ( [1] => a [2] => b [3] => c )
数组$array7的键和值为:

Array ( [one] => a [two] => b [three] => c )
数组$array8的键和值为:

Array ( [0] => a [1] => b [2] => c )

注意:

1>如果用为数组中的一元素指定一个数值作为其键,则此元素之后的所有元素,其默认键为所指定数值的自增的非重复值。

单纯看字面意思有点难理解,让我们来看看一个例子:

以下代码:
代码如下:
1 2 //数组$array4第一个元素的键显示指定为2,之后的第2、3个元素以省略键的方式
3 $array4[2]='a';
4 $array4[]='b';
5 $array4[]='c';
6 //第4个元素的键显示指定为10,之后的第5、6个元素以省略键的方式
7 $array4[10]='d';
8 $array4[]='e';
9 $array4[]='f';
10 //第7个元素的键显示指定为9,之后的第8、9个元素以省略键的方式
11 $array4[9]='g';
12 $array4[]='h';
13 $array4[]='i';
14 //打印数组的键与值
15 print_r($array4);
16 ?>

其结果为:

Array ( [2] => a [3] => b [4] => c [10] => d [11] => e [12] => f [9] => g [13] => h [14] => i )

说明:第七个元素的键为9,正常情况下第八个元素间应该为10,但是键10,11和12之前已有元素使用过,则第八个元素的键为13。

2>无论是以数字还是以字符串作为数组元素的键,其所代表的都只是此元素的键,与此元素在数组中的位置无直接关系,这是与C#等语言中的数组最大的不同之处。下面举个例子。

以下代码:
代码如下:
1 2 $array5['one']='a';
3 if(!isset($array5[0]))
4 {
5 echo '

$array5[0]是空的!

';
6 }
7 ?>

其结果为:

$array5[0]是空的!

说明:$array5[0]所代表的是数组中键为数值0的元素的值(并不像C#等语言代表数组的第一个元素),由于数组只有键为字符串‘one'这一元素,没有元素的键为0,所以$array5[0]是空的。

3>PHP支持两种数组:索引数组(indexed array)和联合数组(associative array),前者使用数字作为键,后者使用字符串作为键。在创建数组时可以混合使用数字和字符串作为元素的键。如下所示代码:
代码如下:
1 2 $array9=array(1=>'a', 2=>'b', 'one'=>'c', 'two'=>'d', 'e', 'f', 'g');
3 echo '

数组$array9的键和值为:

';
4 print_r($array9);
5 ?>

其结果为:

数组$array9的键和值为:

Array ( [1] => a [2] => b [one] => c [two] => d [3] => e [4] => f [5] => g )

4>变量也可以作为数组的键,如下所示:
代码如下:
1 2 $key1='one';
3 $key2='two';
4 $key3='three';
5 $array10[$key1]='a';
6 $array10[$key2]='b';
7 $array10[$key3]='c';
8 echo '

数组$array10的键和值为:

';
9 print_r($array10);
10 ?>

其结果为:

数组$array10的键和值为:

Array ( [one] => a [two] => b [three] => c )

二、如何访问数组的元素

1、 一般方法

要获取数组中的某个元素,只需要使用数组名加中括号加某个键即可,调用方法如下所示:

$arrayname[key];

2、 使用foreach结果遍历数组

如果要访问每个数组元素,可以使用foreach循环:

Foreach($array as $value)

{

//Do something with $value

}

Foreach循环将会迭代数组$array中每个元素,并把每个元素的值赋予$value变量,下面举个例子:
代码如下:
1 2 $array11=array('a','b','c','d','e');
3 echo '

数组$array11的值为:';
4 foreach($array11 as $value)
5 {
6 echo $value.',';
7 }
8 echo '

';
9 ?>

其输出结果为:

数组$array11的值为:a,b,c,d,e,



使用foreach还可以同时访问数组元素的键和值,可以使用:

Foreach($array as $key => $value)

{

//Do something with $key and $value

}

其中$key为每个元素的键,$value元素的值,下面的代码演示如何使用foreach结构创建一个下拉框:
代码如下:
1 2 $array12=array('one'=>1,'two'=>2,'three'=>3,'four'=>4,'five'=>5);
3 echo '';
9 ?>


3、 使用list函数访问数组

List函数是把数组中的值赋给一些变量,其函数语法如下:

Void list(mixed varname, mixed varname2……)

看如下示例:
代码如下:
1 2 $array13=array('red','blue','green');
3 //赋值给所有的变量
4 list($flag1,$sky1,$grassland1)=$array13;
5 echo "$flag1 $sky1 $grassland1";
6 echo '
';
7 //赋值给部分变量
8 list($flag2,,$grassland2)=$array13;
9 echo "$flag2 $grassland2";
10 echo '
';
11 //只赋值给第三个变量
12 list(,,$grassland3)=$array13;
13 echo "$grassland3";
14 echo '
';
15 ?>

输出结果为:

red blue green
red green
green

注意: list() 仅能用于数字索引的数组并且数字索引必须从 0 开始。

因为list函数是先把数组中键为0的元素值赋值给第一个变量,再把键为1的元素值赋值给第二个变量,以此类推,所以list函数中的变量个数和位置必须和数组中的数字键相对应,才能获得想要的值,而且list函数是访问不到以字符串作为键的数组元素的。如下所示:
代码如下:
1 2 $array13=array(1=>'red','blue','green');
3 list($flag1,$sky1,$grassland1)=$array13;
4 echo '$flag1的值为:'.$flag1.'
';
5 echo '$sky1的值为:'.$sky1.'
';
6 echo '$grassland1的值为:'.$grassland1.'
';
7 ?>

其输出结果为:

$flag1的值为:
$sky1的值为:red
$grassland1的值为:blue

说明:因为$flag1的值本应为数组中键为0的元素值,但此数组首元素是以1为键,没有键为0的元素,所以$flag1的值为空,因此也导致后面$sky1和$grassland1的值发生了变化。

4、 使用each函数访问数组

each 函数是返回数组中当前的键/值对并将数组指针向前移动一步,注意是一对,下面详细说明。该函数语法:

array each ( array &$array )

返回 array 数组中当前指针位置的键/值对并向前移动数组指针。每一个键值对被返回为四个单元的数组,键值为 0,1,key 和 value四个元素。元素 0 和 key 包含有数组单元的键名,1 和 value 包含有数据。如果内部指针越过了数组的末端,则 each() 返回 FALSE。这里面为什么each函数有四个下表呢?其实each函数得到这四个下标只是方便我们操作而已,我们可以用0,1作为索引,也可以用key,value作为索引。请看下列代码:
代码如下:
1 2 $arr=array("我是第一个值","我是第二个值","我是第三个值");
3 echo "当我们用0,1为索引时:

";
4 $a=each($arr);
5 echo "我在\$arr数组中的键为:".$a['0'];
6 echo "
";
7 echo "我在\$arr数组中的值为:".$a['1'];
8 echo "

";
9 echo "当我们用key,value为索引时:

";
10 $b=each($arr);
11 echo "我在\$arr数组中的键为:".$b['key'];
12 echo "
";
13 echo "我在\$arr数组中的值为:".$b['value'];
14 ?>

显示为:

当我们用0,1为索引时:
我在$arr数组中的键为:0
我在$arr数组中的值为:我是第一个值
当我们用key,value为索引时:

我在$arr数组中的键为:1
我在$arr数组中的值为:我是第二个值

5、 用each函数与list函数结合来遍历数组,如下例:
代码如下:
1 2 $array14=array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
3 while(list($key,$value) = each($array14))
4 {
5 echo "$key => $value\n";
6 }
7 ?>

其输出结果为:

a => apple b => banana c => cranberry

6、使用for循环访问数组

如下例所示:
代码如下:
1 2 $array15=array('a','b','c','d','e','f');
3 for($i=0;$i4 {
5 echo '数组元素:'.$array15[$i].'
';
6 }
7 ?>

输出结果为:

数组元素:a
数组元素:b
数组元素:c
数组元素:d
数组元素:e
数组元素:f
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

See all articles