关联数组与常规数组的区别
在不必更改函数签名的情况下,如果给定关联数组而不是常规数组,我希望 PHP 函数的行为有所不同。
注意:您可以假设数组是同质的。例如,array(1,2,"foo" => "bar")
不被接受并且可以被忽略。
function my_func(Array $foo){
if (…) {
echo "Found associative array";
}
else {
echo "Found regular array";
}
}
my_func(array("foo" => "bar", "hello" => "world"));
# => "Found associative array"
my_func(array(1,2,3,4));
# => "Found regular array"
这可以用 PHP 实现吗?
Without having to change the function signature, I'd like a PHP function to behave differently if given an associative array instead of a regular array.
Note: You can assume arrays are homogenous. E.g., array(1,2,"foo" => "bar")
is not accepted and can be ignored.
function my_func(Array $foo){
if (…) {
echo "Found associative array";
}
else {
echo "Found regular array";
}
}
my_func(array("foo" => "bar", "hello" => "world"));
# => "Found associative array"
my_func(array(1,2,3,4));
# => "Found regular array"
Is this possible with PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需检查任意键的类型:
Just check the type of any key:
假设
$foo
是同类的,只需检查 one 键的类型即可。Assuming
$foo
is homogeneous, just check the type of one key and that's it.如果您的数组很小并且您不关心开销,您可以使用
array_values
进行检查(如果它们很大,这将非常昂贵,因为它需要复制整个数组只是为了检查,然后处理它):如果您关心内存,您可以这样做:
请注意,这会相当慢,因为它涉及迭代,但它应该具有更高的内存效率,因为它不需要对数组进行任何复制。
考虑到您的同质需求,您可以简单地执行以下操作:
但请注意,数字是关联数组的有效键。我假设您正在谈论带有字符串键的关联数组(这就是上面的 if 将处理的内容)...
You could use a check with
array_values
if your arrays are small and you don't care about the overhead (if they are large, this will be quite expensive as it requires copying the entire array just for the check, then disposing of it):If you care about memory, you could do:
Note that this will be fairly slow, since it involves iteration, but it should be much more memory efficient since it doesn't require any copying of the array.
Considering your homogeneous requirement, you can simply do this:
But note that numerics are valid keys for an associative array. I assume you're talking about an associative array with string keys (which is what the above if will handle)...
根据您的评论
假设数组是同质的;没有混合物。
:只需检查第一个(或最后一个或随机)密钥是整数还是字符串。
In the light of your comment
Assume arrays are homogenous; no mixtures.
:Just check if first (or last, or random) key is an integer or a string.
这是一种方法,通过检查是否有任何由非数字值组成的键:
This would be one way of doing it, by checking if there's any keys consisting of non-numeric values: