Home php教程 php手册 入门知识:动态网页PHP编程中数组的基础知识

入门知识:动态网页PHP编程中数组的基础知识

Jun 21, 2016 am 09:01 AM
array echo foreach gt

关于数组:

PHP中的数组是复杂的,并且比许多其他高级语言中的数组更灵活。
数组array是一组有序的变量,其中每个变量被叫做一个元素。
数组可以被编号或者相关联,也就是数组的元素可以分别根据数字索引或文本化字符串来访问
PHP中,数组可以包含标量(整数,布尔,字符串,浮点数)或复合值(对象甚至其他数组),并且可以包含不同类型的值

1。创建数组

PHP提供创建数组的array()语言结构
$numbers = array(5,4,3,2,1);
$words = array("web","database","application");
echo $numbers[2];
echo $words[0];
---------------------输出结果----------------------------------------
3web
---------------------------------------------------------------------
默认情况下,数组的第一个元素的索引为0。数组中包含的值可以通过使用方括号[]语法来检索和修改
$numbers[5] = 0;
数字化索引的数组可以创建位从任何索引值开始
$numbers = array(1=>"one","two","three","four");
也可以松散的索引
$numbers = array(1=>"one",3=>"three",5=>"zero");
可以通过给变量赋予一个没有参数的array()来创建空数组。然后可以通过使用方括号[]语法来添加值
$error = array();
$error[] = "no error!!!";
$error[] = "second error!!!";
echo $error[0];
echo $error[1];
---------------------输出结果----------------------------------------
no error!!!second error!!!
---------------------------------------------------------------------

2.关联数组

关联数组(associative array)使用字符串索引(或键)来访问存储在数组中的值
关联索引的数组对于数据库层交互非常有用
$newarray = array("first"=>1,"second"=>2,"third"=>3);
echo $newarray["second"];
$newarray["third"]=5;
echo $newarray["third"];
---------------------输出结果----------------------------------------
25
---------------------------------------------------------------------

3.异构数组

PHP数组可以包含不同种类的值
$mixedBag = array("cat",42,8.5,false);
var_dump(mixedBag);

4.多维数组

创建包含数组的数组,数组维数没有限制,但是一般很难想象一个多于三维的数组的用法
$planets = array(array("MM",1,2),array("NN",3,4),array("BB",5,6),array("VV",7,8));
print $planets[2][0];
$planets2 = array("MM"=>array("AA"=>1,"SS"=>2),
"NN"=>array("DD"=>3,"FF"=>4),
"BB"=>array("GG"=>6,"HH"=>7,"PP"=>array("haha!!!!")),
"VV"=>array("JJ"=>6,"KK"=>7,"LL"=>array("one","two")));
print $planets2["VV"]["LL"][0];
---------------------输出结果----------------------------------------
BBone
---------------------------------------------------------------------

5.使用循环访问数组

遍历数组的方法有很多(使用while,for循环)或者foreach语句,最容易的是foreach 语句
$length = array(0,107,202,400,475);
//将厘米转换为寸
for($i=0;$i{
echo ($length[$i]/3);
}
$j=0;
while(isset($length[$j]))
{
echo ($length[$j]/3);
$j++;
}
foreach($length as $cm)
{
echo ($cm/3);
}
---------------------输出结果----------------------------------------
0
35.6666666667
67.3333333333
133.333333333
158.333333333
0
35.6666666667
67.3333333333
133.333333333
158.333333333
0
35.6666666667
67.3333333333
133.333333333
158.333333333

---------------------------------------------------------------------
foreach还可以迭代关联数组的值
$sound = array("cow"=>"moo","dog"=>"woof",
"pig"=>"oink","duck"=>"quack");
foreach ($sound as $animal=>$noice)
{
echo "$animal 得叫声是这样的 $noice $noice......";
}
---------------------输出结果----------------------------------------
cow 的叫声是这样的 moo moo......
dog 的叫声是这样的 woof woof......
pig 的叫声是这样的 oink oink......
duck 的叫声是这样的 quack quack......

---------------------------------------------------------------------

6.使用数组指针

与存储在数组中的键和关联值一起,PHP还拥有一个指向数组当前元素的内部索引,
有几个函数使用并更新该数组索引来提供对数组元素的访问
$a = array("a","b","c","d","e","f");
echo current($a);
each($a);
key($a);//目前数组的指针,返回其索引
echo current($a);//当前元素的值
each($a);//返回当前元素的值并将内部索引指向下一个元素
each($a);
echo current($a);
next($a);//指向下一个元素
echo current($a);
prev($a);//指向上一个元素
echo current($a);
end($a);//指向最后一个元素
echo current($a);
key($a);
echo current($a);
---------------------输出结果----------------------------------------
abdedff
---------------------------------------------------------------------

7.基本的数组函数

integer count(mixed var)//在数组中返回元素的个数,也可用于任何的变量
number max(array numbers)//返回数组中的最大值
number min(array numbers)//返回数组中的最小值
boolean in_array(mixed needle,array haystack[,bollean strict])//查找数组中的值,第三个参数可选,强制执行类型检查
mixed array_search(mixed needle,array haystack[,boolean strict])//返回 键 而不是布尔值,
找不到时返回false,找到的元素如果正好是第一个元素,则返回0,而PHP会自动转化为false所以需要使用===判断,如下
$a = array("a","b","c","d","e","f");
$index = array_search("a",$a);
if($index === false)
echo "在数组a中未发现字符'a'";
else
echo "Index = $index";
---------------------输出结果----------------------------------------
Index = 0
---------------------------------------------------------------------
array array_reverse(array source[,bool preserve_keys])//逆转数组,生成一个新数组,可选参数为true时,保留索引和元素之间的关联
$a = array("a","b","c","d","e","f");
$newa = array_reverse($a);//直接翻转
echo $newa[0];
$newb = array_reverse($a,true);//依旧保留了索引和元素之间的关联
echo $newb[0];
---------------------输出结果----------------------------------------
fa
---------------------------------------------------------------------
sort(array subject[,integer sort_flag])//根据 值 进行升序排列(在原数组中重新排列元素)
rsort(array subject[,integer sort_flag])//根据 值 进行降序排列(在原数组中重新排列元素)
可选参数可以指定为按数字方式SORT_NUMERIC还是字符串方式SORT_STRING或者通常的方式SORT_REGULAR排序
sort()、rsort()可以用于关联数组,但是 键 将丢失
asort(array subject[,integer sort_flag])//根据 值 进行升序排列(在原数组中重新排列元素),保持键值关联
arsort(array subject[,integer sort_flag])//根据 值 进行降序排列(在原数组中重新排列元素),保持键值关联
当asort() arsort()用于非关联数组时,元素按排序后的次序重新排列,但是访问元素的索引不改变
integer ksort(ayyay subject [,integer sort_flag])//根据 键或索引 进行升序排列
integer krsort(ayyay subject [,integer sort_flag])//根据 键或索引 进行降序排列
usort(array subject, string compare_function)//根据用户定义排序,用户定义自己的排序规则函数,但函数必须符合
uasort(array subject, string compare_function)//integer my_compare_function(mixed a, mixed b),a>b返回1,a uksort(array subject, string compare_function)//a等于b时返回0
$numbers = array(16,3,2,171,5,24,6,19);
sort($numbers);
foreach($numbers as $n)
echo $n." ";
$numbers = array(16,3,2,171,5,24,6,19);
rsort($numbers);
foreach($numbers as $n)
echo $n." ";
$numbers = array(16,3,2,171,5,24,6,19);
sort($numbers,SORT_STRING);
foreach($numbers as $n)
echo $n." ";

$a = array("o"=>"kk","e"=>"zz","z"=>"hh","a"=>"rr");
asort($a);
foreach ($a as $keyname=>$keyvalue)
echo $keyvalue;

$a = array("o"=>"kk","e"=>"zz","z"=>"hh","a"=>"rr");
ksort($a);
foreach ($a as $keyname=>$keyvalue)
echo $keyvalue;

//基于长度比较两个字符串
function cmp_length($a,$b)
{
if(strlen($a) return -1;
if(strlen($a) > strlen($b))
return 1;
return 0;
}
$animals = array("cow","ox","monkey","mimi");
usort($animals,"cmp_length");
foreach($animals as $an)
echo $an;
---------------------输出结果----------------------------------------
2 3 5 6 16 19 24 171 171 24 19 16 6 5 3 2 16 171 19 2 24 3 5 6 hhkkrrzzrrzzkkhhoxcowmimimonkey
---------------------------------------------------------------------
array_merge($a,$b)//组合数组,个人认为是比较有趣的函数之一,从两个数组生成一个数组,具有相同 键 的值会被覆盖
////////////////////////////代码部分////////////////////////////////////////
$a = array("name"=>"zhangsan",10,100);
$b = array("name"=>"lisi",4,6,8);
$c = array_merge($a,$b);
var_dump($c);
//////////////////////////////////////////////////////////////////////////
---------------------输出结果----------------------------------------
array(6) { ["name"]=> string(4) "lisi" [0]=> int(10) [1]=> int(100) [2]=> int(4) [3]=> int(6) [4]=> int(8) }
---------------------------------------------------------------------
array array_combine(array $a,array $b)//a数组的值为新数组的键,b数组的值为新数组的值,数组长度不同时,返回false
////////////////////////////代码部分////////////////////////////////////////
$a = array("name","math","china");
$b = array("zhangsan",4,6);
$c = array_combine($a,$b);
var_dump($c);
//////////////////////////////////////////////////////////////////////////
---------------------输出结果----------------------------------------
array(3) { ["name"]=> string(8) "zhangsan" ["math"]=> int(4) ["china"]=> int(6) }
---------------------------------------------------------------------



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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to determine the number of foreach loop in php How to determine the number of foreach loop in php Jul 10, 2023 pm 02:18 PM

​The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Five selected Go language open source projects to take you to explore the technology world Five selected Go language open source projects to take you to explore the technology world Jan 30, 2024 am 09:08 AM

In today's era of rapid technological development, programming languages ​​are springing up like mushrooms after a rain. One of the languages ​​that has attracted much attention is the Go language, which is loved by many developers for its simplicity, efficiency, concurrency safety and other features. The Go language is known for its strong ecosystem with many excellent open source projects. This article will introduce five selected Go language open source projects and lead readers to explore the world of Go language open source projects. KubernetesKubernetes is an open source container orchestration engine for automated

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

Go language development essentials: 5 popular framework recommendations Go language development essentials: 5 popular framework recommendations Mar 24, 2024 pm 01:15 PM

"Go Language Development Essentials: 5 Popular Framework Recommendations" As a fast and efficient programming language, Go language is favored by more and more developers. In order to improve development efficiency and optimize code structure, many developers choose to use frameworks to quickly build applications. In the world of Go language, there are many excellent frameworks to choose from. This article will introduce 5 popular Go language frameworks and provide specific code examples to help readers better understand and use these frameworks. 1.GinGin is a lightweight web framework with fast

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

See all articles