Home Backend Development PHP Tutorial Array array and using foreach loop array graphic example detailed explanation

Array array and using foreach loop array graphic example detailed explanation

Jun 22, 2017 pm 03:35 PM
array foreach use cycle array

1. 了解数组

        PHP 中的数组实际上是一个有序映射。映射是一种把 values 关联到 keys 的类型。

2.例子:一般的数组

       这里,我通过一个简单的例子,并使用图形方式来了解数组。

//1.-----------------------------------
$a = array(3 => 'a', 1 => 'b', 2 => 'c');
echo var_dump($a);
Copy after login

[注]:使用箭头描述数组$a各个单元对应某一内存地址的数据值(实际上,它内部结构采用HashTable结构)。

3.例子:在数组定义中,添加引用。

//2.-----------------------------------

$x = 'x';
$a = array(3 => 'a', 1 => &$x, 2 => 'c');

echo "<hr>";
echo var_dump($a);

$x = &#39;y&#39;;
echo var_dump($a);
Copy after login

数组$a中的第2个单元$a[1]与$x对应的是同一个数据,使用var_dump($a)的时候,会看到数组的第2个单元多个&符号,即&string(1) "x",表示引用。

当 修改$x的值='y',也等同于修改$a[1]的值='y'。

下图可以清楚的描述这一变化:

4.例子:使用foreach遍历数组

//3.-----------------------------------

$a = array(3 => &#39;a&#39;, 1 => &#39;b&#39;, 2 => &#39;c&#39;);

echo "<hr>";
foreach ($a as $key => $value) {
    echo "$key => $value <br>";

}
Copy after login

每次循环中,当前数组中单元的值被赋给 $value ,单元的key被赋给$key。如下图描述:

【注:】灰色虚箭头表示赋予某一值。

5.例子:在foreach遍历数组中,使用引用赋值。

//4.-----------------------------------

$a = array(3 => &#39;a&#39;, 1 => &#39;b&#39;, 2 => &#39;c&#39;);

echo "<hr>";
foreach ($a as $key => &$value) {
    $value.=&#39;n&#39;;
    echo "$key => $value <br>";

}
Copy after login

每次循环中, $value 都指向当前数组中单元的值,再执行“ $value.='n'; ”代码 ,如下图描述:

6.例子:对例子5的进一步分析。

在例子5,foreach遍历数组完成后,不会自动销毁$value变量,与数组$a最后一个单元$a[2]指向同一个数据。

这时候改变$value的值,也就是改变了$a[2]的值。

//5.-----------------------------------

$value=&#39;m&#39;;

echo "<hr>";
echo "\$value=$value <br>";
echo var_dump($a);
Copy after login

实例验证, 数组最后一个元素的 $value 引用在 foreach 循环之后仍会保留。建议使用 unset() 来将其销毁。 

 7.小结

以上例子,只是描述php中的array数组和foreach的一些特性。学习最后,感觉php中的array数组和foreach不同于别的编程语言,不能使用类似C语言的结构分析PHP。

 

The above is the detailed content of Array array and using foreach loop array graphic example detailed explanation. For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

What is Bitget Launchpool? How to use Bitget Launchpool? What is Bitget Launchpool? How to use Bitget Launchpool? Jun 07, 2024 pm 12:06 PM

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

See all articles