array_walk()函数何时会返回false?官方文档释义与测试验证
array_walk() return false? Great question! Let's break this down clearly, since it's easy to mix up how array_walk() handles return values.
First, let's reference the official documentation (as you noted):
成功时返回TRUE,失败时返回FALSE。
The key point here is that false is only returned when the function itself cannot execute properly—not when your callback returns false, or when the input array is empty (like your test case).
Scenarios where array_walk() returns false:
- The first argument is not an array: If you pass a non-array value (string, integer, null, etc.), the function will fail and return
false(along with a PHP warning).
Example:var_dump(array_walk("this is a string", function($val) {})); // Outputs bool(false) - The second argument is not a valid callable: If you pass a value that can't be invoked as a function (e.g., a non-existent function name, an integer, an array that doesn't represent a valid method),
array_walk()will returnfalse.
Example:var_dump(array_walk([1, 2, 3], "some_non_existent_function")); // Outputs bool(false)
Why your test case returned true:
In your code:
$array = []; var_dump(array_walk($array, function($val) {return $val;})); // bool(true)
Even though the array is empty, all parameters are valid: you passed an array, and a valid anonymous callback. array_walk() executes successfully (it just has no elements to iterate over), so it returns true.
Also, keep in mind: the return value of your callback is ignored by array_walk(). Returning false from the callback only stops the iteration early—it doesn't make array_walk() itself return false.
内容的提问来源于stack exchange,提问作者Houssem ZITOUN

