php数组有哪些赋值方式

原创
ithorizon 8个月前 (09-04) 阅读数 107 #PHP

PHP数组赋值做法全解析

在PHP中,数组是一种非常灵活的数据结构,它用于存储一系列值。PHP数组赞成多种赋值做法,下面将详细介绍这些赋值方法。

1. 数字索引数组赋值

数字索引数组是PHP中最单纯的数组类型,它的索引是自动分配的整数。

$numbers = array(1, 2, 3, 4, 5);

// 或者使用短数组语法(PHP 5.4+)

$numbers = [1, 2, 3, 4, 5];

2. 相关性数组赋值

相关性数组使用字符串作为索引,每个索引都相关性一个值。

$colors = array(

"red" => "#FF0000",

"green" => "#00FF00",

"blue" => "#0000FF"

);

// 短数组语法

$colors = [

"red" => "#FF0000",

"green" => "#00FF00",

"blue" => "#0000FF"

];

3. 多维数组赋值

多维数组可以看作是数组的数组,即一个数组中的元素也是数组。

$students = array(

array("name" => "Alice", "age" => 20),

array("name" => "Bob", "age" => 22),

array("name" => "Charlie", "age" => 23)

);

// 短数组语法

$students = [

["name" => "Alice", "age" => 20],

["name" => "Bob", "age" => 22],

["name" => "Charlie", "age" => 23]

];

4. 使用索引赋值

可以明确指定数组的索引进行赋值。

$fruits[0] = "apple";

$fruits[1] = "orange";

$fruits[2] = "banana";

5. 使用array_push()函数

使用array_push()函数可以在数组的末尾插入一个或多个元素。

$fruits = array();

array_push($fruits, "apple");

array_push($fruits, "orange", "banana");

6. 遍历赋值

可以遍历一个已有的数组,并对每个元素进行操作后赋值给新的数组。

$numbers = array(1, 2, 3, 4, 5);

foreach ($numbers as $key => $value) {

$squaredNumbers[$key] = $value * $value;

}

7. 使用列表赋值

列表赋值允许你在一条语句中给多个变量赋值,这些变量可以用来创建数组。

list($a, $b, $c) = array(1, 2, 3);

// 短数组语法

list($a, $b, $c) = [1, 2, 3];

以上就是PHP中常见的数组赋值做法,灵活运用这些方法可以让你在编程中更加得心应手。


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: PHP


热门