PHP current() 函数
最后修改于 2025 年 3 月 13 日
PHP 的 current 函数返回数组中当前元素的 **值**。它是 PHP 数组指针函数的一部分。
基本定义
current 函数获取由内部指针当前指向的数组元素的 **值**。它 **不** 移动指针。
语法:current(array|object $array): mixed。该函数返回当前元素的**值**,如果数组为空或出现错误则返回 **false**。
基本的 current() 示例
此示例演示了如何从简单数组中获取当前元素。
basic_current.php
<?php $fruits = ['apple', 'banana', 'cherry']; // Set pointer to first element reset($fruits); $current = current($fruits); echo "Current fruit: $current";
我们首先使用 reset 将数组指针重置到开头。然后 current 返回 'apple',即第一个元素的值。
在循环中使用 current()
展示 current 如何与其他指针函数一起使用。
current_in_loop.php
<?php
$colors = ['red', 'green', 'blue'];
// Set pointer to first element
reset($colors);
while ($color = current($colors)) {
echo "Color: $color\n";
next($colors);
}
此示例使用 current 和 next 循环遍历数组。输出按顺序显示所有三种颜色。
关联数组示例
演示 current 与关联数组的用法。
associative_array.php
<?php
$user = [
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 30
];
reset($user);
echo "First value: " . current($user);
对于关联数组,current 返回第一个元素的**值**,无论其键是什么。在这里,它返回 'John Doe'。
数组修改后的 Current
展示数组修改如何影响当前元素。
modification_effect.php
<?php $numbers = [10, 20, 30]; reset($numbers); echo "Current: " . current($numbers) . "\n"; // 10 // Modify array array_unshift($numbers, 5); echo "Current after modification: " . current($numbers); // 5
向数组开头添加元素会移动内部指针。在调用 array_unshift 后,当前元素从 10 变为 5。
空数组与 Current
演示 current 在空数组中的行为。
empty_array.php
<?php $empty = []; $result = current($empty); var_dump($result);
当在空数组上调用时,current 返回 **false**。在处理可能为空的数组时,检查此返回值非常重要。
最佳实践
- 重置指针:始终首先使用
reset重置指针。 - 检查返回值:验证返回值,因为它可能为 false。
- 组合函数:与
next、prev结合使用进行遍历。 - 避免修改:在迭代期间不要修改数组。
来源
本教程通过实际示例介绍了 PHP current 函数,展示了其在数组遍历场景中的用法。
作者
列出 所有 PHP 数组函数。