Home php教程 php手册 php数组操作学习笔记

php数组操作学习笔记

Jun 13, 2016 am 10:16 AM
php getting Started study Summarize operate array of notes

小编今天给大家来总结php中数组操作的一些入门学习笔记了,包括了:数据创建,赋值,遍历,查找,统计,多维数组等等在php中数组各种操作,有需要了解的朋友可参考。

什么是数组?

数组是一个数据的集合,相当于一个容器,可以将数据按一定的规则存到这个容器中。相当于旅馆,旅馆内有很多房间,而房间按照一定的规则编号。

数组的构成:基本结构形式如下:

$数组名 (键)= 值 数组名:是一个数组区别于另一个数组的方式,就像每个旅馆都有一个名字。
键(key):也成为指针、索引或者标识符。键代表某值在数组中存放的位置,相当于旅馆的门牌号,可以用不同方式命名。通过查询键可以找到相应的值。
值(value):值相当于房间内存放的东西。

赋值创建数组

在php中,创建数组有变量赋值和调用函数两种方法,这里先讲前者。

使用变量赋值方法很简单,直接给一个数组变量赋值即可。

实例:

 代码如下 复制代码

 $lang[]="php";
 $lang[]="html";
 $lang[]="css";
 echo "$lang[0]
";
 echo "$lang[1]
";
 echo "$lang[2]
";
?>

三个赋值语句产生的数组内容:

0=>php

1=>html

2=>css

创建数组

除了上面介绍的赋值创建数组,还有调用函数的方法创建数组。

php提供了array函数来穿件一个数组,基本结构形式如下:

array (item1,item2... ,itemn)

/* item表示数组中的元素值。array()函数创建数组时自动给元素值分配标识符,从0依次增加 */
实例:

 代码如下 复制代码

 $student=array("Tom","Jacky","Rose");
 echo $student[0] ."t";
 echo $student[1] ."t";
 echo $student[2];
?>

数组键名

1、键名分配

在用array()函数创建数组时,键名会自动分配到各个值。另外,我们也可以按自己的需要直接给元素分配键名。

基本结构形式:

array ( key => item )

实例1:

 代码如下 复制代码
   $a=array(1 => "you",2 =>"are ", 5 =>"how ");
 echo $a[5];
 echo $a[2];
 echo $a[1];
?>

2、用字符串作键名

不但可以用整数作为键名,也可以使用字符串作为键名。使用字符串作为键名的数组成为字符串索引(string-indexed)数组。

实例2:

 代码如下 复制代码
 $a=array("php"=>"动态网页","html"=>"静态网页","css"=>"网页排版");
 echo $a["php"] ."
";
 echo $a["html"] ."
";
 echo $a["css"];
?>

3、键名的修改

实例3:

 代码如下 复制代码

 $arr = array("a" => "新浪",   
   "b"=>"网易",    
   "c" => "腾讯", "雅虎"  
  );
  $arr[a] = "PHP中文社区";  
  $arr['e'] = "新浪";   
  $arr[] = "百度";    
 echo $arr['a'] ."
";   
 echo $arr['b'] ."
";   
 echo $arr['c'] ."
";   
 echo $arr['e'] ."
";   
 echo $arr[0] ."
";    
 echo $arr[1] ."
";    
?>

创建多维数组

在php程序编写时,一维数组有时不能满足需求,这时就要用到多维数组。多维数组就是在一维数组的基础上再增加一个或多个细下标,用法与一维数组大致相同,只是多维数据操作更为复杂,不过功能更强大。

以二维数组为例,就像大房子里面套有小房子,表示方法为$a[0][0]。

实例:

 代码如下 复制代码

 $a[0][0]=1;
 $a[0][1]=2;
 $a[0][2]=3;
 $a[1][0]=4;
 $a[1][1]=5;
 $a[1][2]=6;
 for($i=0;$i   for($j=0;$j    echo "$a[$i][$j]=" .$a[$i][$j] ."
"; /* "$"表示输出变量符号$ */
  }
 }
?>

输出数组

输出数组是指将数组的的所有元素数据显示在浏览器上,php怎么输出数组?常用的php输出数组函数有var_dump()和print_r()函数。

1、var_dump函数递归展开数组元素,显示数组各元素的类型、键名和元素值。

实例1:

 代码如下 复制代码
 $a=array(0,5,array("php","html","css")); /* 创建一个嵌套的数组 */
 var_dump($a);
?>

2、print_r函数值显示数组元素的键名和元素值。

实例2:

 代码如下 复制代码


 $b=array(1,2,3);
 print_r($b);
?>

测试数组


有时候我们不清楚某个变量是不是数组,可以用is_array()函数来测试判断。

基本结构形式:

is_array ( 变 量 )

检测变量是否数组,如果是则返回true,否则返回false。

实例:

 代码如下 复制代码

 $a="apple iphone";
 if(is_array($a)){
   var_dump($a);
  }
 else echo "不是数组";
?>

foreach遍历数组


我们在运用数组时,常常要遍历数组并获得各个键或者元素值,php提供了一些专门遍历数组的函数。这里先介绍foreach遍历数组函数的用法。

结构形式:

 代码如下 复制代码


 foreach ( array_expression as $value ) statement
/* array_expression是要遍历的数组
   as作用是将数组的值赋给$value
   statement是后续语句
 */
实例1:

   $color=array('white' => '白色' ,
       'black' => '黑色' ,
       'red' => '红色' ,
       'green' => '绿色',
       'yellow' => '黄色');
 foreach( $color as $c) echo $c ."
";   
?>

通过foreach不仅可以获得元素的值也可以获得键名,结构形式:

  foreach ( array_expression as $key => $value ) statement

将以上实例中第7行的代码:

 

 代码如下 复制代码

 foreach( $color as $c) echo $c ."
";
改为:


 foreach( $color as $key => $c) echo $key.$c ."
";


查找数组元素值

php获取数组键名可以用array_search()来实现,结构形式如下:

array_search( $needle,$haystack )
/* 参数$needle表示要查找的值 */
/* $haystack表示查找对象 */
array_search()函数返回的是键名,而不是布尔值,找不到时返回false。找到的元素如果正好是第一个元素,则返回0。而php会自动转化成false,所以需要使用”===”判断返回值。(“===”判断是否全等,详:php关系运算符)

实例:

 代码如下 复制代码

 $s=array("a","b","c","d","e","f");
 $i=array_search("a",$s); /* 查找数组是否有字符"a" */
 if($i===false)  /* 判断查找结果 */
  echo "在数组s中找不到字符'a'";
 else echo "输出数组$s的键名:" .$i; /* 输出键名 */ 
?>

计算数组元素个数

数组也像变量一样可以进行运算,例如需要php统计数组元素个数时,我们可以利用count()函数来计算数组中元素的个数。

结构形式:

 代码如下 复制代码


 count ( $var,$mode )
/* $var参数$var通常是一个数组,函数返回var中的单元数目 */
/* mode是可选参数 */
实例:

 $a=array("peple","man","women");
 $b=count($a); /* 统计数组元素个数 */
 echo $b;
?>

数组排序

php提供了一系列的数组排序函数,我们可以根据需要对数组进行排序。数组的排序主要有三种方式:

按键值排序

即按标识符ASCⅡ码值的大小排列顺序。

ksort(): 按照数组标识符顺序排列
krsort(): 按照数组标识符逆序排
实例1:

 代码如下 复制代码
 $languages=array(
  'c'=>'php',
  'd'=>'asp',
  'a'=>'jsp',
  'b'=>'java'
 );
 krsort($languages);
 foreach($languages as $key=>$val){
  echo "$key = $val".'
';
 };
?>

按元素值排序

 asort(): 按照由小到大的顺序对数组排序;
rsort(): 按照由大到小的顺序对数组逆序排序。
将实例1的8-11行代码改为:

 

 代码如下 复制代码
  asort($languages);
 print_r($languages);
 echo "
";
 rsort($languages);
 print_r($languages);

删除原有键名排序

 sort(): 按照由小到大的顺序对数组排序;
rsort(): 按照由大到小的顺序对数组逆序排序。
将实例2的8-11行代码改为:

 

 代码如下 复制代码

sort($languages);
 foreach($languages as $key=>$val){
  echo "languages[$key] = $val".'
';
 };

 

数组运算符

合并数组计算实例:

 代码如下 复制代码
 $a=array(
   'a'=>'php',
   'b'=>'html',
   'c'=>'css'
 );
 $b=array(
   'a'=>'asp',
   'b'=>'jsp'
 );
 $c=$a+$b; /* 合并数组 */
 var_dump($c);
 echo "
";
 $c=$b+$a; /* 调换顺序合并数组 */
 var_dump($c); 
?>

数组的比较实例:

 代码如下 复制代码
 $a=array('php','asp');
 $b=array(1=>'asp',0=>'php');
 var_dump($a==$b);
 var_dump($a===$b);
?>

数组运算符
例子 名称 结果
$a + $b 联合 $a 和 $b 的联合。
$a == $b 相等 如果 $a 和 $b 具有相同的键/值对则为 TRUE
$a === $b 全等 如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE
$a != $b 不等 如果 $a 不等于 $b 则为 TRUE
$a $b 不等 如果 $a 不等于 $b 则为 TRUE
$a !== $b 不全等 如果 $a 不全等于 $b 则为 TRUE
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles