检查$ var =数组中的任何内容?

时间:2011-10-23 18:04:03

标签: php wordpress

我需要能够测试$ post_count是否等于给定数组中的任何数字。这是我想要实现的一个例子:

$posts_even = array(2,4,6,8,10);
$posts_odd = array(1,3,5,7,9);
$posts_ev3 = array(1,4,7,10);
$posts_ev4 = array(1,5,9);

-

$post_count=1;
$post_count=++; //in wordpress loop so each subsequent post is +1

-

if ($post_count= //any value in $posts_ev4) :
    echo 'this'
else :
    NULL;
endif;

我已经能够使用or运算符来完成这项工作,但我最终得到了很长的代码块......

if (($post_count=1) || ($post_count=2)) :
    echo 'this'
else :
    NULL;
endif;

我猜有一种更简单的方法可以做到这一点,但我是PHP的新手,所以我不确定!任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:3)

使用in_array()检查数组中是否存在值。

答案 1 :(得分:3)

尝试:

if (in_array($post_count, $post_ev4)) {}

请参阅:in_array()

答案 2 :(得分:1)

if (in_array($post_count, $posts_ev4)) :
    echo 'this'
else :
    NULL;
endif;

答案 3 :(得分:1)

查看PHP Manual中的isset()函数。

答案 4 :(得分:1)

php中有数组函数。 Ypu可以使用“is_array”函数来检查它的数组是否存在。 &安培;要检查一个值,你可以使用“in_array”函数。

if(is_array($array) && in_array($post_count,$array))
{  
   // do operation
}