PHP array_push 函数
最后修改于 2025 年 3 月 13 日
PHP array_push
函数用于向数组末尾添加一个或多个元素。这是一种将值追加到现有数组的便捷方法。
基本定义
array_push
函数将元素推送到数组的末尾。它会修改原始数组并返回新元素的数量。
语法: array_push(array &$array, mixed ...$values): int
。第一个参数是要修改的数组,后面是要添加的值。
array_push 基本示例
这演示了如何使用 array_push 向数组添加单个元素。
basic_array_push.php
<?php $fruits = ["apple", "banana"]; $count = array_push($fruits, "orange"); print_r($fruits); // Output: Array ( [0] => apple [1] => banana [2] => orange ) echo "New count: $count"; // Output: New count: 3
这会将 "orange" 添加到 $fruits 数组中。该函数返回 3,即新元素的数量。原始数组已修改。
添加多个元素
array_push 可以一次向数组添加多个元素。
multiple_elements.php
<?php $numbers = [1, 2]; $newCount = array_push($numbers, 3, 4, 5); print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) echo "New count: $newCount"; // Output: New count: 5
这会将三个数字 (3, 4, 5) 添加到 $numbers 数组中。该函数返回数组中新元素的总数为 5。
将 array_push 与关联数组一起使用
array_push 在关联数组上的行为与在索引数组上有所不同。
associative_array.php
<?php $user = ["name" => "John", "age" => 30]; $count = array_push($user, "New York"); print_r($user); // Output: Array ( [name] => John [age] => 30 [0] => New York )
对于关联数组,array_push 使用数字键添加元素。“New York” 值获得索引 0,因为它是第一个数字索引元素。
使用 [] 的替代语法
对于添加单个元素,[] 语法通常比 array_push 更简单。
alternative_syntax.php
<?php $colors = ["red", "green"]; $colors[] = "blue"; // Equivalent to array_push($colors, "blue") print_r($colors); // Output: Array ( [0] => red [1] => green [2] => blue )
对于单个元素,[] 语法更简洁,但 array_push 对于多个元素更好。两者都会修改原始数组。
性能注意事项
array_push 与 [] 语法的性能特征不同。
performance.php
<?php $largeArray = range(1, 100000); // Test array_push $start = microtime(true); array_push($largeArray, 100001); $timePush = microtime(true) - $start; // Test [] syntax $start = microtime(true); $largeArray[] = 100001; $timeBracket = microtime(true) - $start; echo "array_push: " . $timePush . " seconds\n"; echo "[] syntax: " . $timeBracket . " seconds\n";
对于单个元素,[] 通常比 array_push 速度更快。但是,对于多个元素,array_push 可能比多个 [] 操作更有效。
最佳实践
- 多个元素: 使用 array_push 一次添加多个值。
- 单个元素: 倾向于使用 [] 语法,以获得更简洁的代码。
- 返回值: 在需要时使用计数返回值。
- 关联数组: 了解数字键的行为。
来源
本教程涵盖了 PHP array_push
函数,并提供了实用示例,展示了它如何用于向数组添加元素。
作者
列出 所有 PHP 数组函数。