search
HomeBackend DevelopmentPHP Tutorial PHP数组的定义、初始化和数组元素的展示

PHP数组的定义、初始化和数组元素的显示

从ASP初入门到PHP,感觉到PHP的强大之一就是内置函数的丰富,比如先前学习的PHP日期时间函数,读写文件的相关函数等都无不表明了PHP的更专业、更令用户的使用得心应手。

一开始我对PHP函数的丰富功能很兴奋,随着对越来越多近乎变态多的函数接触之后,突然联想到了ASP内置函数的稀少,要完成某项特殊功能,常须自定义函数,随着应用的在增多,自己居然也有了一套常用的函数库。然而现在在PHP中,这些功能早已被标准化、规范化而浓缩为内置函数直接使用,曾经的ASP开发人员成为了PHP的普通用户。

但转念一想,这些函数、这些大量PHP函数的存在,至少说明了PHP的更专业;同时,在我们日常PHP程序处理时应该是很快捷易用的吧,这让开发人员不再为些基础功能、细节功能而去自定义函数,把主要的精力集中在组建更强大的程序模块上。所以,我更加坚定了一看PHP函数到底的信念,不过我想在以后的开发过程中,PHP函数手册应该属于随身书了。

当然,关于ASP和PHP孰优孰劣的争论就无需多讨论,学习并了解能让自己了解真相。

言正传,PHP函数太多,防止遗忘,所以每次看完一类函数后我都做个总结和收集工作,方便起见就写篇日志。

1,数组的定义和初始化

什么是数组?数组是一种编程结构,它是一个存储一组或一系列数值的变量。

比如人口普查时对个人的身份登记,如姓名、性别、民族、出生等就可作为数组。

PHP中创建数组使用array()结构来定义,比如:


$people=array('name','sex','nation','brith');


而如何显示数组中的各元素的值,我们则是使用从0开始的索引,索引号在变量名称后的方括号中,比如:


$people=array('name','sex','nation','birth');
echo $people[2];
?>


输出的$people[2]就是显示的是nation(索引第一项从0计数)。

PHP除了支持数字索引数组以外,还支持相关数组。所谓相关数组,就是可自定义关键字来替换不直观的数字索引,比如:


$peoples=array('xm'=>'name','xb'=>'sex','mz'=>'nation','cs'=>'birth');
echo $peoples['cs'];
?>


使用相关数组使得输出的选择很直观(不需要预先计算索引号然后输出),定义的关键字和值之间使用“=>”符号定义。

根据PHP数组元素的两种显示方式,还可以如变量一样无需array()声明和初始化,直接自动创建数字。比如


$people[0]='name';
$people[1]='sex';
$people[2]='nation';
$people[3]='brith';


或者


$peoples['xm']='name';
$peoples['xb']='sex';
$peoples['mz']='nation';
$peoples['cs']='birth';


该数组的大小根据所增加元素的多少动态的变化。

2,数组元素的显示

在如上使用的无论$people[2]也好,无论$peoples['cs']也好,都只是输出已知的明确位置的数组元素值,如何快速输出所有或部分的数组元素,使用循环语句无疑是最快的方法。


$people=array('name','sex','nation','birth');
for ($i=0;$i????echo "$people[$i] ";
?>


除了使用了解循环次数的for循环以外,还可以使用对循环次数无须要求的foreach语句。


$people=array('name','sex','nation','birth');
foreach($people as $xiangmu)
????echo $xiangmu;
?>


$xiangmu变量将保存数组中的各元素值,依次显示出来。当然,为了输出的数据能间隔区分,可在数组元素之后输出空格:
echo $xiangmu." ";
注:英文句号(.)可将字符串连接合并成新的字符串,参见亲密接触PHP之变量、常量学习笔记

Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),