如何检查变量是否是数组?...或类似数组的东西 [英] How to check if variable is array?... or something array-like

查看:51
本文介绍了如何检查变量是否是数组?...或类似数组的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一个变量使用 foreach 循环,但是这个变量可以是许多不同的类型,例如 NULL.

I want to use a foreach loop with a variable, but this variable can be many different types, NULL for example.

所以在 foreach 之前我测试了一下:

So before foreach I test it:

if(is_array($var)){
  foreach($var as ...

但我意识到它也可以是一个实现了Iterator接口的类.也许我瞎了,但是如何检查类是否实现了接口?是否有类似 is_a 函数或 inherits 运算符的东西?我找到了 class_implements,我可以使用它,但也许有更简单的东西?

But I realized that it can also be a class that implements Iterator interface. Maybe I am blind but how to check whether the class implements interface? Is there something like is_a function or inherits operator? I found class_implements, I can use it, but maybe there is something simpler?

第二,更重要的是,我认为这个函数存在,足以检查变量 is_array 或实现 Iterator 接口"还是我应该测试某些东西更多?

And second, more important, I suppose this function exist, would be enough to check if the variable is_array or "implements Iterator interface" or should I test for something more?

推荐答案

如果您在函数中使用 foreach 并且您需要一个数组或一个 Traversable 对象,你可以输入提示该函数:

If you are using foreach inside a function and you are expecting an array or a Traversable object you can type hint that function with:

function myFunction(array $a)
function myFunction(Traversable)

如果您没有在函数内使用 foreach 或者您期望 你可以简单地使用这个结构来检查你是否可以迭代变量:

If you are not using foreach inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:

if (is_array($a) or ($a instanceof Traversable))

这篇关于如何检查变量是否是数组?...或类似数组的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆