PHP is a server-side scripting language that is widely used in Web server-side programming. In PHP, array is an important data structure. We can create and operate arrays in many ways. This article will introduce one of them: setting the array through key-value pairs.
1. Create an array
$a = []; $b = array();
$a = [1, 2, 3]; $b = ['name' => '张三', 'age' => 20];
$a = [1, 'name' => '张三', 2, 'age' => 20];
2. Set the array elements
$a = []; $a[0] = 1; $a[1] = 'hello'; $a[2] = ['a' => 1, 'b' => 2];
$a = ['name' => '张三', 'age' => 20]; $a['address'] = '北京市朝阳区';
$a = []; $a[] = 1; // 等价于 $a[0] = 1; $a[] = 'hello'; // 等价于 $a[1] = 'hello'; $a['name'] = '张三'; // 等价于 $a['name'] = '张三';
3. Access array elements
$a = [1, 'hello', ['a' => 1, 'b' => 2]]; echo $a[0]; // 输出1 echo $a[1]; // 输出hello echo $a[2]['a']; // 输出1
$a = ['name' => '张三', 'age' => 20]; echo $a['name']; // 输出张三 echo $a['age']; // 输出20
4. Traverse the array elements
$a = [1, 2, 3]; for ($i = 0; $i < count($a); $i++) { echo $a[$i], ' '; // 输出:1 2 3 }
$a = ['name' => '张三', 'age' => 20]; foreach ($a as $key => $value) { echo $key, ': ', $value, PHP_EOL; // 输出:name: 张三,age: 20 }
$a = [1, 2, 3]; while (list($key, $value) = each($a)) { echo $key, ': ', $value, PHP_EOL; // 输出:0: 1,1: 2,2: 3 }
The above is the relevant content of setting the array through key-value pairs. I hope to be helpful. PHP provides a variety of ways to create and operate arrays. Only by mastering them can you better write efficient PHP programs.
The above is the detailed content of php set array mode. For more information, please follow other related articles on the PHP Chinese website!