Home Backend Development PHP Tutorial PHP数组循环操作详细介绍 附实例代码_php技巧

PHP数组循环操作详细介绍 附实例代码_php技巧

May 17, 2016 am 09:07 AM
php array cycle

PHP数组还是比较常用的,于是我研究了一下PHP数组循环操作,在这里拿出来和大家分享一下,希望对大家有用。PHP基本上就是一种数组语言。时常要进行大量的PHP数组循环操作,主要有两种方式,一种是foreach,另一种是while,到底哪种好哪种坏一直有争论,虽然我很早就意识到了这个问题,但是一直没有细究,懵懂的感觉一直持续到现在,为了以后能节省点CPU时间,下面总结一下:

在循环里进行的是数组“读”操作,则foreach比while快,PHP数组循环操作无格式查看复制到剪贴板打印代码?

复制代码 代码如下:

foreach($arrayas$value){
echo$value;
}
while(list($key)=each($array)){
echo$array[$key];
}
foreach($arrayas$value){
echo$value;
}
while(list($key)=each($array)){
echo$array[$key];
}

在循环里进行的是数组“写”操作,则while比foreach快:

无格式查看复制到剪贴板打印代码?
复制代码 代码如下:

foreach($arrayas$key=>$value){
echo$array[$key]=$value.'...';
}
while(list($key)=each($array)){
$array[$key]=$array[$key].'...';
}
foreach($arrayas$key=>$value){
echo$array[$key]=$value.'...';
}
while(list($key)=each($array)){
$array[$key]=$array[$key].'...';
}

总结:通常认为,foreach涉及到值复制,一定会比while慢,但实际上,如果仅仅是在循环里进行数组的读操作,那么foreach是很快的,这是因为PHP采用的复制机制是“引用复制,写时拷贝”,这样看来,foreach的高效读操作就不难理解了。另外,既然foreach不适合处理数组写操作,那么我们可以得出一个结论,多数情况下,类似foreach($arrayas$key=>$value)形式的代码都应该被替换成while(list($key)=each($array))。

这些技巧产生的速度差异在小项目里可能并不明显,但是在类似框架这样的大项目中,一次请求动辄便会涉及到几百几千几万次数组循环操作,差异就会明显放大。

有关php数组及循环的小例子,包括二维数组、杨辉三角、获取参数、矩形对角线求和,有需要的朋友建议看看

复制代码 代码如下:

//1、使用循环语句,输出任意一个二维数组 。
$arr=array(
array(1,2,3,4),
array(5,6,7,8),
array(9,10,11,12),
array(13,14,15,16)
);
foreach ($arr as $var){
foreach ($var as $val1){
echo "$val1 ";
}
echo "
";
}
echo "
";
//2、使用循环控制语句,输出杨辉三角。
function yanghuisanjiao($line){
$sc[][]=array();
$sc[0][0]=1;
for($i=1;$ifor($j=0;$jif($j==0 or $i==$j){
$sc[$i][$j]=1; //把每行的第一个数字和最后一个数字设为1
}else{
$sc[$i][$j]=$sc[$i-1][$j-1]+$sc[$i-1][$j];
}
}
}
foreach ($sc as $value){
foreach($value as $v1){
echo $v1.' ';
}
echo '

';
}
}
yanghuisanjiao(5);
echo "
";
//3、使用循环和预定义变量,获取多个参数。参数的个数未定。
function avg(){
$ags=func_get_args();
$sum=0;
foreach ($ags as $v){
$sum+=$v;
}
return '平均值是:'.$sum/func_num_args();
}
echo avg(1,2,3,4,5,6,7);

//4、使用循环输出一个二维数组,并求该矩形对角线元素的和。
function getSum($theCount){
$b=0;
echo '

';
echo "";
for($i=1;$iecho "";
for($j=1;$j   if($j==$i || $theCount+1-$i==$j){
    echo "";
    $b=$b+$j;
    if($j==$i && $theCount+1-$i==$j){
     $b=$b+$j;
    }
   }
   else{
    echo "";
   }
}
echo "";
}
echo "
$j$j
";
echo "对角线元素之和为:".$b;
}
getSum(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

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)

How to determine how many arrays there are in php How to determine how many arrays there are in php Aug 04, 2023 pm 05:40 PM

There are several ways to determine an array in PHP: 1. Use the count() function, which is suitable for all types of arrays. However, it should be noted that if the parameter passed in is not an array, the count() function will return 0; 2. Use the sizeof() function, which is more used to maintain compatibility with other programming languages; 3. Custom functions, By using a loop to traverse the array, each time it is traversed, the counter is incremented by 1, and finally the length of the array is obtained. Custom functions can be modified and expanded according to actual needs, making them more flexible.

How to convert a two-dimensional php array into a one-dimensional array How to convert a two-dimensional php array into a one-dimensional array Aug 03, 2023 am 11:14 AM

How to convert a php array from two dimensions to a one-dimensional array: 1. Use loop traversal to traverse the two-dimensional array and add each element to the one-dimensional array; 2. Use the "array_merge" function to merge multiple arrays into An array. Pass the two-dimensional array as a parameter to the "array_merge" function to convert it into a one-dimensional array; 3. Using the "array_reduce" function, you can process all the values ​​in the array through a callback function and finally return a result.

An exploration of performance optimization techniques for PHP arrays An exploration of performance optimization techniques for PHP arrays Mar 13, 2024 pm 03:03 PM

PHP array is a very common data structure that is often used during the development process. However, as the amount of data increases, array performance can become an issue. This article will explore some performance optimization techniques for PHP arrays and provide specific code examples. 1. Use appropriate data structures In PHP, in addition to ordinary arrays, there are some other data structures, such as SplFixedArray, SplDoublyLinkedList, etc., which may perform better than ordinary arrays in certain situations.

What are php array key-value pairs? What are php array key-value pairs? Aug 03, 2023 pm 02:20 PM

PHP array key-value pair is a data structure consisting of a key and a corresponding value. The key is the identifier of the array element, and the value is the data associated with the key. It allows us to store and access data using keys as identifiers. By using key-value pairs, we can more easily operate and manage elements in the array, making program development more flexible and efficient.

Lambda expression breaks out of loop Lambda expression breaks out of loop Feb 20, 2024 am 08:47 AM

Lambda expression breaks out of the loop, specific code examples are needed. In programming, the loop structure is an important syntax that is often used. However, in certain circumstances, we may want to break out of the entire loop when a certain condition is met within the loop body, rather than just terminating the current loop iteration. At this time, the characteristics of lambda expressions can help us achieve the goal of jumping out of the loop. Lambda expression is a way to declare an anonymous function, which can define simple function logic internally. It is different from an ordinary function declaration,

What is the function in PHP to determine if an array is empty? What is the function in PHP to determine if an array is empty? Aug 03, 2023 pm 05:15 PM

The functions that PHP uses to determine if an array is empty are the "empty()" function and the "count()" function. 1. The "empty()" function is used to determine whether a variable is empty, including determining whether an array is empty. Its syntax is "empty($variable)"; 2. The "count()" function is used to count arrays. The number of elements, the syntax is "count($array)".

PHP returns all the values ​​in the array to form an array PHP returns all the values ​​in the array to form an array Mar 21, 2024 am 09:06 AM

This article will explain in detail how PHP returns all the values ​​of an array to form an array. 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. Using the array_values() function The array_values() function returns an array of all the values ​​in an array. It does not preserve the keys of the original array. $array=["foo"=>"bar","baz"=>"qux"];$values=array_values($array);//$values ​​will be ["bar","qux"]Using a loop can Use a loop to manually get all the values ​​of the array and add them to a new

Will shuffling the order of PHP array affect the reference or address of the array? Will shuffling the order of PHP array affect the reference or address of the array? Apr 30, 2024 pm 03:48 PM

No, shuffling a PHP array order will not affect element references or addresses, since the elements and their keys remain unchanged. After shuffling, the contents of the array (elements and keys) remain unchanged, only the order of the keys changes.

See all articles