Home >Backend Development >PHP Problem >How to assign values to a two-dimensional array in php
In PHP programming, array (Array) is a very commonly used data type and a data structure. PHP arrays can store values of different data types, including numbers, strings, objects, functions, and other arrays.
Two-dimensional array is a form of array. It is an array composed of multiple one-bit arrays. It can be regarded as a table containing multiple rows and columns of data, such as students in a class. List information.
In PHP, creating a two-dimensional array is simple. The following are several methods of assigning two-dimensional arrays:
This method defines the value of each element directly when the array is initialized.
// 定义一个二维数组 $nameList = array( array('小明',18,'男'), array('小红',20,'女'), array('小兰',19,'女') ); // 输出二维数组的元素 echo $nameList[0][0]; // 输出'小明' echo $nameList[1][1]; // 输出'20' echo $nameList[2][2]; // 输出'女'
This method is assignment one by one, which can be achieved through loop statements or manual addition.
// 通过循环语句逐个赋值 $nameList = array(); for ($i=0; $i<3; $i++) { $nameList[$i] = array(); $nameList[$i][0] = '姓名'.$i; $nameList[$i][1] = '年龄'.$i; $nameList[$i][2] = '性别'.$i; } // 手动添加的方式逐个赋值 $nameList = array(); $nameList[0] = array('小明',18,'男'); $nameList[1] = array('小红',20,'女'); $nameList[2] = array('小兰',19,'女'); // 输出二维数组的元素 echo $nameList[0][0]; // 输出'小明' echo $nameList[1][1]; // 输出'20' echo $nameList[2][2]; // 输出'女'
This method is to dynamically assign values during the running of the program and can be implemented through some functions.
// 使用array_push()函数动态添加数组元素 $nameList = array(); array_push($nameList, array('小明',18,'男')); array_push($nameList, array('小红',20,'女')); array_push($nameList, array('小兰',19,'女')); // 输出二维数组的元素 echo $nameList[0][0]; // 输出'小明' echo $nameList[1][1]; // 输出'20' echo $nameList[2][2]; // 输出'女'
The above three methods are common ways to assign two-dimensional arrays in PHP. No matter which method is used, you need to understand the basic operations of arrays in PHP in order to process two-dimensional array data more flexibly and efficiently.
The above is the detailed content of How to assign values to a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!