Table of Contents
1. foreach()
2. while()
3. for()
key()
reset()
each()
current(),next(),prev(),end()
Home Backend Development PHP Tutorial PHP 遍历数组的方法汇总

PHP 遍历数组的方法汇总

Jun 23, 2016 pm 01:41 PM

1. foreach()

foreach()是一个用来遍历数组中数据的最简单有效的方法。

#example1:

$colors= array('red','blue','green','yellow');

foreach ($colorsas$color){

echo "Do you like $color?
";

}

?>


显示结果:

Do you like red? 
Do you like blue? 
Do you like green? 
Do you like yellow?

2. while()

while() 通常和 list(),each()配合使用。

#example2:

$colors= array('red','blue','green','yellow');

while(list($key,$val)= each($colors)) {

echo "Other list of $val.
";

}

?>

显示结果:

Other list of red. 
Other list of blue. 
Other list of green. 
Other list of yellow.

3. for()

#example3:

$arr= array ("0"=> "zero","1"=> "one","2"=> "two");

for ($i= 0;$i

$str= $arr[$i];

echo "the number is $str.
";

}

?>

显示结果:

the number is zero. 
the number is one. 
the number is two.

========= 以下是函数介绍 ==========

key()

mixed key(array input_array)

key()函数返回input_array中位于当前指针位置的键元素。

#example4

$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");

echo "

Can you name the capitals of these states?

";

while($key= key($capitals)) {

echo $key."
";

next($capitals);

//每个key()调用不会推进指针。为此要使用next()函数

}

?>

显示结果:

Can you name the capitals of these states? 
Ohio 
Towa 
Arizona

reset()

mixed reset(array input_array)

reset()函数用来将input_array的指针设置回数组的开始位置。如果需要在一个脚本中多次查看或处理同一个数组,就经常使用这个函数,另外这个函数还常用于排序结束时。

#example5 - 在#example1上追加代码

$colors= array('red','blue','green','yellow');

foreach ($colorsas$color){

echo "Do you like $color?
";

}

reset($colors);

while(list($key,$val)= each($colors)) {

echo "$key=> $val
";

}

?>

显示结果:

Do you like red? 
Do you like blue? 
Do you like green? 
Do you like yellow? 
0 => red 
1 => blue 
2 => green 
3 => yellow

注意:将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上例中如果我们在循环内部将 $colors 赋给了另一个变量的话将会导致无限循环。 
例如将 $s1 = $colors; 添加到while循环内,再次执行代码,浏览器就会无休止地显示结果。

each()

array each(array input_array)

each()函数返回输入数组当前键/值对,并将指针推进一个位置。返回的数组包含四个键,键0和key包含键名,而键1和value包含相应的数据。如果执行each()前指针位于数组末尾,则返回FALSE。

#example6

$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");

$s1= each($capitals);

print_r($s1);

?>

显示结果:

Array ( [1] => Columbus [value] => Columbus [0] => Ohio [key] => Ohio )

current(),next(),prev(),end()

mixed current(array target_array)

current()函数返回位于target_array数组当前指针位置的数组值。与next()、prev()、和end()函数不同,current()不移动指针。 
next()函数返回紧接着放在当前数组指针的下一个位置的数组值。 
prev()函数返回位于当前指针的前一个位置的数组值,如果指针本来就位于数组的第一个位置,则返回FALSE。 
end()函数将指针移向target_array的最后一个位置,并返回最后一个元素。

#example7

$fruits= array("apple","orange","banana");

$fruit= current($fruits); //return "apple"

echo $fruit."
";

$fruit= next($fruits); //return "orange"

echo $fruit."
";

$fruit= prev($fruits); //return "apple"

echo $fruit."
";

$fruit= end($fruits); //return "banana"

echo $fruit."
";

?>

显示结果:

apple 
orange 
apple 
banana

=========== 下面来测试三种遍历数组的速度 ===========

一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间。

测试环境: 
Intel Core Due2 2GHz 
2GB 1067MHz DDR3 
Mac OS X 10.5.7 
Apache 2.0.59 
MySQL 5.0.41 
PHP 5.2.6

#example8

$arr= array();

for($i= 0; $i

$arr[]= $i*rand(1000,9999);

}

function GetRunTime()

{

list($usec,$sec)=explode(" ",microtime());

return ((float)$usec+(float)$sec);

}

######################################

$time_start= GetRunTime();

for($i= 0; $i

$str= $arr[$i];

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of for:'.round($time_used, 7).'(s)

';

unset($str, $time_start, $time_end, $time_used);

######################################

$time_start= GetRunTime();

while(list($key, $val)= each($arr)){

$str= $val;

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of while:'.round($time_used, 7).'(s)

';

unset($str, $key, $val, $time_start, $time_end, $time_used);

######################################

$time_start= GetRunTime();

foreach($arr as$key=> $val){

$str= $val;

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of foreach:'.round($time_used, 7).'(s)

';

?>

测试结果:

Used time of for:0.0228429(s)

Used time of while:0.0544658(s)

Used time of foreach:0.0085628(s)

经过反复多次测试,结果表明,对于遍历同样一个数组,foreach速度最快,最慢的则是while。从原理上来看,foreach是对数组副本进行操作(通过拷贝数组),而while则通过移动数组内部指标进行操作,一般逻辑下认为,while应该比foreach快(因为foreach在开始执行的时候首先把数组复制进去,而while直接移动内部指标。),但结果刚刚相反。原因应该是,foreach是PHP内部实现,而while是通用的循环结构。所以,在通常应用中foreach简单,而且效率高。在PHP5下,foreach还可以遍历类的属性。


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

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months 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)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

See all articles