search
HomeBackend DevelopmentPHP TutorialPHP遍历数组的几种方法_php技巧

PHP中遍历数组有三种常用的方法:
一、使用for语句循环遍历数组;
二、使用foreach语句遍历数组;
三、联合使用list()、each()和while循环遍历数组。
这三种方法中效率最高的是使用foreach语句遍历数组。从PHP4开始就引入了foreach结构,是PHP中专门为遍历数组而设计的语句,推荐大家使用。先分别介绍这几种方法。

一、使用for语句循环遍历数组
值得大家注意的是使用for语句循环遍历数组要求遍历的数组必须是索引数组。PHP中不仅有关联数组而且还有索引数组,所以PHP中很少用for语句循环遍历数组。
实例代码如下:

复制代码 代码如下:

$arr = array('http://www.jb51.net','脚本之家','PHP教程');
$num = count($arr);
for($i=0;$iecho $arr[$i].'
';
}
?>

注释:上例代码中我们先计算出数组$arr中元素的个数,然后才使用在for语句,这样做很高效的。因为如果是for($i=0;$i上面代码的输出结果为:
http://www.jb51.net
脚本之家
PHP教程

二、使用foreach语句遍历数组
使用foreach语句循环遍历数组有二种方式,我们使用的最多的还是第一种方式。介绍如下:
第一种方式:
foreach(array_expression as $value){
//循环体
}
实例代码:
复制代码 代码如下:

$arr = array('http://www.jb51.net','脚本之家','PHP教程');
foreach($arr as $value){
echo $value.'
';
}
?>


每次循环中,当前元素的值被赋给变量$value,并且把数组内部的指针向后移动一步。所以下一次循环中会得到数组的下一个元素,直到数组的结尾才停止循环,结束数组的遍历。

第二种方式:
foreach(array_expression as $key=>$value){
//循环体
}
实例代码:
复制代码 代码如下:

//定义数组
$arr = array('http://www.jb51.net','脚本之家','PHP教程');
foreach($arr as $k=>$v){
echo $k."=>".$v."
";
}
?>


三、联合使用list()、each()和while循环遍历数组
each()函数需要传递一个数组作为一个参数,返回数组中当前元素的键/值对,并向后移动数组指针到下一个元素的位置。
list()函数,这不是一个真正的函数,是PHP的一个语言结构。list()用一步操作给一组变量进行赋值。

实例代码:
复制代码 代码如下:

//定义循环的数组
$arr = array('website'=>'http://www.jb51.net','webname'=>'脚本之家')
while(list($k,$v) = each($arr)){
echo $k.'=>'.$v.'
';
}
?> jb51.net

输出结果为:
website=>http://www.jb51.net
webname=>PHP程序员

总结:上述三种循环遍历数组的方法中建议大家使用foreach语句循环遍历数组,效率更高。
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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),

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!