简体   繁体   中英

Check if $var = anything in an array?

I need to be able to test if $post_count is equal to any number in a given array. Here is an example of what I am trying to achieve:

$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;

I have been able to make this work using the or operator but I end up with very long blocks of code.....

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

I am guessing there is a simpler way to do this but I am new to PHP so I am not sure! Any help would be greatly appreciated.

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

Try:

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

See: in_array()

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

查看PHP手册中的isset()函数。

There are array functions in php. Ypu can use "is_array" function to check whether its array or not. & to check for a value you can use "in_array" function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM