Home Backend Development PHP Tutorial 第五章 php数组操作_PHP

第五章 php数组操作_PHP

Jun 01, 2016 pm 12:14 PM
php array

一.什么是数组
数组是一组有某种共同特性的元素,包括相似性和类型。
每个元素由一个特殊的标识符来区分,称之为key,而每个key都有一个value
1.创建数组的两种方式:
1.1 用array()函数
复制代码 代码如下:
$usernames = array ('Alerk', 'Mary', 'Lucy', 'Bob', 'Jack', 'John', 'Mark' );
foreach ( $usernames as $name )
{
echo $name . '
';
}
?>

output
Alerk
Mary
Lucy
Bob
Jack
John
Mark
1.2 用range()函数
复制代码 代码如下:
$numbers = range ( 0, 10 );
foreach ( $numbers as $num )
{
echo $num . '
';
}
$letters = range ( 'a', 'z' );
foreach ( $letters as $letter )
{
echo $letter . '
';
}
?>

output
0
1
2
3
4
5
6
7
8
9
10
a

c
d
e
f
g
h
i
j
k
l
m

o

q
r

t
u
v
w
x
y
z
2.循环访问数组元素的两种方式:
2.1 for循环
复制代码 代码如下:
//range的第三个参数表示步长
$numbers = range(1,10,2);
for($i = 0;$i{
echo $numbers[$i].'
';
}
?>

output
1
3
5
7
9
2.2 foreach循环
复制代码 代码如下:
$letters = range('a','h',2);
foreach($letters as $letter)
{
echo $letter.'
';
}
?>

output
a
c
e
g
Foreach还可以用来输出数组的下标和对应的值
复制代码 代码如下:
$letters = range('a','g',2);
foreach($letters as $key => $value)
{
echo $key.'---'.$value.'
';
}
?>

output
0---a
1---c
2---e
3---g
3.is_array()函数,用于变量判断是否为一个数组
复制代码 代码如下:
$numbers = range(1,10,2);
if(is_array($numbers))
{
foreach($numbers as $num)
{
echo $num.'
';
}
}
else
{
echo $numbers;
}
?>

4.print_r函数,打印关于变量的易于理解的信息
复制代码 代码如下:
$usernames = array ('Jackie', 'Mary', 'Lucy', 'Bob', 'Mark', 'John' );
print_r ( $usernames );
?>

output
Array ( [0] => Jackie [1] => Mary [2] => Lucy [3] => Bob [4] => Mark [5] => John )
源代码里可以看到显示为:
Array
(
[0] => Jackie
[1] => Mary
[2] => Lucy
[3] => Bob
[4] => Mark
[5] => John
)
二.自定义键数组
1.如果不想创建默认下标为零的数组,可以用如下方法,创建键为字符串的数组
复制代码 代码如下:
//初始化数组
$userages = array('Jack'=> 23,'Lucy'=>25,'Mark'=>28);
//访问数组各元素
echo $userages['Jack'].'
';
echo $userages['Lucy'].'
';
echo $userages['Mark'].'
';
?>

2.往自定义键数组里追加元素
复制代码 代码如下:
//初始化数组
$ages = array('Jack'=>23);
//追加元素
$ages['Lucy']=25;
$ages['Mark']=28;
foreach($ages as $key => $value)
{
echo $key.'----'.$value.'
';
}
?>

3.直接添加元素,无需创建数组。
复制代码 代码如下:
//不创建数组直接添加
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
foreach($ages as $key => $value)
{
echo $key.'----'.$value.'
';
}
?>

4.循环打印数组foreach的使用
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
foreach($ages as $key => $value)
{
echo $key.'=>'.$value.'
';
}
?>

5. each() -- 返回数组中当前的键/值对并将数组指针向前移动一步
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
$a = each($ages);
print_r($a);
echo '
';
$a = each($ages);
print_r($a);
echo '
';
$a = each($ages);
print_r($a);
?>

用each()函数做循环打印
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
while(!! $element = each($ages))
{
print_r($element);
echo '
';
}
?>

另一种打印方式
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
while(!! $element = each($ages))
{
echo $element['key'].'=>'.$element['value'];
echo '
';
}
?>

6.list()函数的使用--把数组中的值赋给一些变量
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
list($name,$age)= each($ages);
echo $name.'=>'.$age;
?>

用list循环打印结果
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
while(!!list($name,$age)= each($ages))
{
echo $name.'=>'.$age.'
';
}
?>

output
Jack=>23
Lucy=>25
Mark=>28
7.reset()函数的使用--将数组的内部指针指向第一个单元
复制代码 代码如下:
$ages['Jack']=23;
$ages['Lucy']=25;
$ages['Mark']=28;
each($ages);
each($ages);
list($name,$age)= each($ages);
echo $name.'=>'.$age.'
';
//把数组重新设定到数组开始处
reset($ages);
list($name,$age)= each($ages);
echo $name.'=>'.$age.'
';
?>

Output
Mark=>28
Jack=>23
8. array_unique() -- 移除数组中重复的值
复制代码 代码如下:
$nums = array(1,2,3,4,5,6,5,4,3,2,1,1,2,3,4,5,6);
//返回一个不包含重复值的数组
$result = array_unique($nums);
print_r($result);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
9. array_flip ()-- 交换数组中的键和值
$userages = array('Jack'=> 23,'Lucy'=>25,'Mark'=>28);
$ages = array_flip($userages);
print_r($ages);
?>

output
Array ( [23] => Jack [25] => Lucy [28] => Mark )
三.数组里的数组
数组里不一定就是一个关键字和值的列表,数组里也可以放入数组
复制代码 代码如下:
$produces = array(
array('apple',6,28.8),
array('pear',3,15.6),
array('banana',10,4.6)
);
echo $produces[0][0].'|'.$produces[0][1].'|'.$produces[0][2].'
';
echo $produces[1][0].'|'.$produces[1][1].'|'.$produces[1][2].'
';
echo $produces[2][0].'|'.$produces[2][1].'|'.$produces[2][2].'
';
?>

output
apple|6|28.8
pear|3|15.6
banana|10|4.6
用for循环打印数组中的数组
复制代码 代码如下:
$produces = array (
array ('apple', 6, 28.8 ),
array ('pear', 3, 15.6 ),
array ('banana', 10, 4.6 )
);
for($i = 0; $i {
for($j = 0; $j {
echo '|' . $produces[$i][$j];
}
echo '
';
}
?>

output
|apple|6|28.8
|pear|3|15.6
|banana|10|4.6
二维数组
复制代码 代码如下:
$produces = array (
array ('name' => 'apple', 'amount' => 6, 'price' => 28.8 ),
array ('name' => 'pear', 'amount' => 3, 'price' => 15.6 ),
array ('name' => 'banana', 'amount' => 10, 'price' => 4.6 )
);
while(!!List($key,$value)=each($produces))
{
while(!!list($key2,$value2)=each($value))
{
echo '|'.$key2.'=>'.$value2;
}
echo '
';
}
?>

output
|name=>apple|amount=>6|price=>28.8
|name=>pear|amount=>3|price=>15.6
|name=>banana|amount=>10|price=>4.6
用foreach来打印则更容易(推荐)
复制代码 代码如下:
$produces = array (
array ('name' => 'apple', 'amount' => 6, 'price' => 28.8 ),
array ('name' => 'pear', 'amount' => 3, 'price' => 15.6 ),
array ('name' => 'banana', 'amount' => 10, 'price' => 4.6 )
);
foreach($produces as $key1 => $value1)
{
foreach($value1 as $key2 => $value2)
{
echo '|'.$key2.'=>'.$value2;
}
echo '
';
}
?>

output
|name=>apple|amount=>6|price=>28.8
|name=>pear|amount=>3|price=>15.6
|name=>banana|amount=>10|price=>4.6
四.数组的排序
1.Sort()函数对英文的排序
复制代码 代码如下:

$fruits = array('lemo','banana','apple','pear');
echo '原始的数组:';
print_r($fruits);
echo '
';
sort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [0] => lemo [1] => banana [2] => apple [3] => pear )
排序后的数组:Array ( [0] => apple [1] => banana [2] => lemo [3] => pear )
2.Sort()函数对中文的排序
复制代码 代码如下:

$fruits = array('柠檬','香蕉','苹果','梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
sort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

Output:
原始的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 )
排序后的数组:Array ( [0] => 柠檬 [1] => 梨子 [2] => 苹果 [3] => 香蕉 )
3. asort -- 对数组进行排序并保持索引关系
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
asort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
排序后的数组:Array ( [a] => 柠檬 [d] => 梨子 [c] => 苹果 [b] => 香蕉 )
4. ksort -- 对数组按照键名排序
复制代码 代码如下:

$fruits = array('b'=>'柠檬','a'=>'香蕉','d'=>'苹果','c'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
ksort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [b] => 柠檬 [a] => 香蕉 [d] => 苹果 [c] => 梨子 )
排序后的数组:Array ( [a] => 香蕉 [b] => 柠檬 [c] => 梨子 [d] => 苹果 )
5. rsort -- 对数组逆向排序
复制代码 代码如下:

$fruits = array('柠檬','香蕉','苹果','梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
rsort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 )
排序后的数组:Array ( [0] => 香蕉 [1] => 苹果 [2] => 梨子 [3] => 柠檬 )
6. arsort -- 对数组进行逆向排序并保持索引关系
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
arsort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
排序后的数组:Array ( [b] => 香蕉 [c] => 苹果 [d] => 梨子 [a] => 柠檬 )
7. krsort -- 对数组按照键名逆向排序
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
krsort($fruits);
echo '排序后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
排序后的数组:Array ( [d] => 梨子 [c] => 苹果 [b] => 香蕉 [a] => 柠檬 )
8. shuffle -- 将数组打乱
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
shuffle($fruits);
echo '打乱后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
打乱后的数组:Array ( [0] => 香蕉 [1] => 苹果 [2] => 柠檬 [3] => 梨子 )
9. array_reverse -- 返回一个单元顺序相反的数组
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
$fruits = array_reverse($fruits);
echo '反转后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
反转后的数组:Array ( [d] => 梨子 [c] => 苹果 [b] => 香蕉 [a] => 柠檬 )
10. array_unshift -- 在数组开头插入一个或多个单元
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
array_unshift($fruits,'杮子');
echo '插入后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
插入后的数组:Array ( [0] => 杮子 [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
11. array_shift -- 将数组开头的单元移出数组
复制代码 代码如下:

$fruits = array('a'=>'柠檬','b'=>'香蕉','c'=>'苹果','d'=>'梨子');
echo '原始的数组:';
print_r($fruits);
echo '
';
array_shift($fruits);
echo '移出后的数组:';
print_r($fruits);
?>

output
原始的数组:Array ( [a] => 柠檬 [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
移出后的数组:Array ( [b] => 香蕉 [c] => 苹果 [d] => 梨子 )
12. array_rand -- 从数组中随机取出一个或多个单元
复制代码 代码如下:

$fruits = array ('柠檬', '香蕉', '苹果', '梨子' );
echo '原始的数组:';
print_r ( $fruits );
echo '
';
$newArr_key = array_rand ( $fruits, 2 );
echo '随机后的数组:';
echo $fruits [$newArr_key [0]].' ';
echo $fruits [$newArr_key [1]];
?>

output
原始的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 )
随机后的数组:梨子 苹果
13. array_pop -- 将数组最后一个单元弹出(出栈)
复制代码 代码如下:

$fruits = array ('柠檬', '香蕉', '苹果', '梨子' );
echo '原始的数组:';
print_r ( $fruits );
echo '
';
array_pop ( $fruits );
echo '弹出后的数组:';
print_r ( $fruits );
?>

Output:
原始的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 )
弹出后的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 )
14. array_push -- 将一个或多个单元压入数组的末尾(入栈)
复制代码 代码如下:

$fruits = array ('柠檬', '香蕉', '苹果', '梨子' );
echo '原始的数组:';
print_r ( $fruits );
echo '
';
array_push ( $fruits,'杮子');
echo '弹出后的数组:';
print_r ( $fruits );
?>

Output:
原始的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 )
弹出后的数组:Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 [4] => 杮子 )
五.数组的指针的操作
each -- 返回数组中当前的键/值对并将数组指针向前移动一步
current -- 返回数组中的当前单元
reset -- 将数组的内部指针指向第一个单元
end -- 将数组的内部指针指向最后一个单元
next -- 将数组中的内部指针向前移动一位
pos -- current() 的别名
prev -- 将数组的内部指针倒回一位

复制代码 代码如下:
$fruits = array ('柠檬', '香蕉', '苹果', '梨子' );
print_r ( $fruits );
echo '
';
echo 'each() : ';
print_r ( each ( $fruits ) );
echo '
';
echo 'current() : ';
echo (current ( $fruits ));
echo '
';
echo 'next() : ';
echo (next ( $fruits ));
echo '
';
echo 'end() : ';
echo (end ( $fruits ));
echo '
';
echo 'prev() : ';
echo (prev ( $fruits ));
echo '
';
echo 'pos() : ';
echo (pos ( $fruits ));
echo '
';
?>

Output:
Array ( [0] => 柠檬 [1] => 香蕉 [2] => 苹果 [3] => 梨子 )
each() : Array ( [1] => 柠檬 [value] => 柠檬 [0] => 0 [key] => 0 )
current() : 香蕉
next() : 苹果
end() : 梨子
prev() : 苹果
pos() : 苹果
六.统计数组个数
count -- 计算数组中的单元数目或对象中的属性个数
sizeof -- count() 的别名
array_count_values -- 统计数组中所有的值出现的次数
复制代码 代码如下:
$nums = array (1, 3, 5, 1, 3, 4, 5, 65, 4, 2, 2, 1, 4, 4, 1, 1, 4, 1, 5, 4, 5, 4 );
echo count ( $nums );
echo '
';
echo sizeof ( $nums );
echo '
';
$arrayCount = array_count_values ( $nums );
print_r ( $arrayCount );
?>

output
22
22
Array ( [1] => 6 [3] => 2 [5] => 4 [4] => 7 [65] => 1 [2] => 2 )
七.将数组转换成标量变量:extract()
把数组中的每个元素转换成变量,变量名是数组元素的key,变量值为数组元素的value.
复制代码 代码如下:
$fruits = array('a'=>'apple','b'=>'banana','o'=>'orange');
extract($fruits);
echo $a.'
';
echo $b.'
';
echo $o.'
';
?>

output
apple
banana
orange

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 use PHP arrays to generate and display charts and statistical graphs How to use PHP arrays to generate and display charts and statistical graphs Jul 15, 2023 pm 12:24 PM

How to use PHP arrays to generate and display charts and statistical graphs. PHP is a widely used server-side scripting language with powerful data processing and graphic generation capabilities. In web development, we often need to display charts and statistical graphs of data. Through PHP arrays, we can easily implement these functions. This article will introduce how to use PHP arrays to generate and display charts and statistical graphs, and provide relevant code examples. Introducing the necessary library files and style sheets Before starting, we need to introduce some necessary library files into the PHP file

How to use PHP arrays to generate dynamic slideshows and image displays How to use PHP arrays to generate dynamic slideshows and image displays Jul 15, 2023 pm 01:17 PM

How to use PHP arrays to generate dynamic slideshows and picture displays. Slideshows and picture displays are common functions in web design and are often used in scenarios such as carousels and gallery displays. As a popular server-side scripting language, PHP has the ability to process data and generate dynamic HTML pages, and is very suitable for generating dynamic slideshows and picture displays. This article will introduce how to use PHP arrays to generate dynamic slideshows and picture displays, and give corresponding code examples. Prepare image data First, we need to prepare a set of image path data

How to use PHP arrays to implement user login and permission management functions How to use PHP arrays to implement user login and permission management functions Jul 15, 2023 pm 08:55 PM

How to use PHP arrays to implement user login and permission management functions When developing a website, user login and permission management are one of the very important functions. User login allows us to authenticate users and protect the security of the website. Permission management can control users' operating permissions on the website to ensure that users can only access the functions for which they are authorized. In this article, we will introduce how to use PHP arrays to implement user login and permission management functions. We'll use a simple example to demonstrate this process. First we need to create

What are the functions for averaging arrays in php? What are the functions for averaging arrays in php? Jul 17, 2023 pm 04:03 PM

PHP array averaging functions include: 1. array_sum(), which is used to calculate the sum of all values ​​in the array. In order to calculate the average, you can add all the values ​​in the array and then divide by the number of array elements; 2 , array_reduce(), used to iterate the array and calculate each value with an initial value; 3. array_mean(), used to return the average of the array, first calculate the sum of the array, and calculate the number of array elements, then The sum is divided by the number of array elements to get the average.

How to determine how many arrays there are in php How to determine how many arrays there are in php Aug 04, 2023 pm 05:40 PM

There are several ways to determine an array in PHP: 1. Use the count() function, which is suitable for all types of arrays. However, it should be noted that if the parameter passed in is not an array, the count() function will return 0; 2. Use the sizeof() function, which is more used to maintain compatibility with other programming languages; 3. Custom functions, By using a loop to traverse the array, each time it is traversed, the counter is incremented by 1, and finally the length of the array is obtained. Custom functions can be modified and expanded according to actual needs, making them more flexible.

An exploration of performance optimization techniques for PHP arrays An exploration of performance optimization techniques for PHP arrays Mar 13, 2024 pm 03:03 PM

PHP array is a very common data structure that is often used during the development process. However, as the amount of data increases, array performance can become an issue. This article will explore some performance optimization techniques for PHP arrays and provide specific code examples. 1. Use appropriate data structures In PHP, in addition to ordinary arrays, there are some other data structures, such as SplFixedArray, SplDoublyLinkedList, etc., which may perform better than ordinary arrays in certain situations.

What are php array key-value pairs? What are php array key-value pairs? Aug 03, 2023 pm 02:20 PM

PHP array key-value pair is a data structure consisting of a key and a corresponding value. The key is the identifier of the array element, and the value is the data associated with the key. It allows us to store and access data using keys as identifiers. By using key-value pairs, we can more easily operate and manage elements in the array, making program development more flexible and efficient.

What is the function in PHP to determine if an array is empty? What is the function in PHP to determine if an array is empty? Aug 03, 2023 pm 05:15 PM

The functions that PHP uses to determine if an array is empty are the "empty()" function and the "count()" function. 1. The "empty()" function is used to determine whether a variable is empty, including determining whether an array is empty. Its syntax is "empty($variable)"; 2. The "count()" function is used to count arrays. The number of elements, the syntax is "count($array)".

See all articles